Comparison

util/throttle.lua @ 4952:0e9a5b63206a

util.throttle: floor() internal balance calculation
author Matthew Wild <mwild1@gmail.com>
date Mon, 09 Jul 2012 02:35:47 +0100
parent 4467:fc8a22936b3c
child 6777:5de6b93d0190
comparison
equal deleted inserted replaced
4950:02e5e9fa37b8 4952:0e9a5b63206a
1 1
2 local gettime = require "socket".gettime; 2 local gettime = require "socket".gettime;
3 local setmetatable = setmetatable; 3 local setmetatable = setmetatable;
4 local floor = math.floor;
4 5
5 module "throttle" 6 module "throttle"
6 7
7 local throttle = {}; 8 local throttle = {};
8 local throttle_mt = { __index = throttle }; 9 local throttle_mt = { __index = throttle };
9 10
10 function throttle:update() 11 function throttle:update()
11 local newt = gettime(); 12 local newt = gettime();
12 local elapsed = newt - self.t; 13 local elapsed = newt - self.t;
13 self.t = newt; 14 self.t = newt;
14 local balance = self.rate * elapsed + self.balance; 15 local balance = floor(self.rate * elapsed) + self.balance;
15 if balance > self.max then 16 if balance > self.max then
16 self.balance = self.max; 17 self.balance = self.max;
17 else 18 else
18 self.balance = balance; 19 self.balance = balance;
19 end 20 end