2 local gettime = require "socket".gettime;
7 local throttle_mt = { __index = throttle };
9 function throttle:update()
10 local newt = gettime();
11 local elapsed = newt - self.t;
13 local balance = self.rate * elapsed + self.balance;
14 if balance > self.max then
15 self.balance = self.max;
17 self.balance = balance;
22 function throttle:peek(cost)
24 return self.balance >= cost or self:update() >= cost;
27 function throttle:poll(cost, split)
28 if self:peek(cost) then
29 self.balance = self.balance - cost;
32 local balance = self.balance;
36 return false, balance, (cost-self.balance);
40 function create(max, period)
41 return setmetatable({ rate = max / period, max = max, t = 0, balance = max }, throttle_mt);