2 local gettime = require "socket".gettime;
3 local setmetatable = setmetatable;
4 local floor = math.floor;
9 local throttle_mt = { __index = throttle };
11 function throttle:update()
12 local newt = gettime();
13 local elapsed = newt - self.t;
15 local balance = floor(self.rate * elapsed) + self.balance;
16 if balance > self.max then
17 self.balance = self.max;
19 self.balance = balance;
24 function throttle:peek(cost)
26 return self.balance >= cost or self:update() >= cost;
29 function throttle:poll(cost, split)
30 if self:peek(cost) then
31 self.balance = self.balance - cost;
34 local balance = self.balance;
38 return false, balance, (cost-balance);
42 function create(max, period)
43 return setmetatable({ rate = max / period, max = max, t = 0, balance = max }, throttle_mt);