2 local gettime = require "socket".gettime;
3 local setmetatable = setmetatable;
8 local throttle_mt = { __index = throttle };
10 function throttle:update()
11 local newt = gettime();
12 local elapsed = newt - self.t;
14 local balance = self.rate * elapsed + self.balance;
15 if balance > self.max then
16 self.balance = self.max;
18 self.balance = balance;
23 function throttle:peek(cost)
25 return self.balance >= cost or self:update() >= cost;
28 function throttle:poll(cost, split)
29 if self:peek(cost) then
30 self.balance = self.balance - cost;
33 local balance = self.balance;
37 return false, balance, (cost-balance);
41 function create(max, period)
42 return setmetatable({ rate = max / period, max = max, t = 0, balance = max }, throttle_mt);