diff --git a/timer.lua b/timer.lua index 01be11f..fd1b163 100644 --- a/timer.lua +++ b/timer.lua @@ -24,46 +24,52 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ]]-- -local functions = {} -local function update(dt) +local Timer = {} +Timer.__index = Timer + +local function new() + return setmetatable({functions = {}}, Timer) +end + +function Timer:update(dt) local to_remove = {} - for func, delay in pairs(functions) do + for func, delay in pairs(self.functions) do delay = delay - dt if delay <= 0 then to_remove[#to_remove+1] = func end - functions[func] = delay + self.functions[func] = delay end for _,func in ipairs(to_remove) do - functions[func] = nil + self.functions[func] = nil func(func) end end -local function add(delay, func) - assert(not functions[func], "Function already scheduled to run.") - functions[func] = delay +function Timer:add(delay, func) + assert(not self.functions[func], "Function already scheduled to run.") + self.functions[func] = delay return func end -local function addPeriodic(delay, func, count) +function Timer:addPeriodic(delay, func, count) local count = count or math.huge -- exploit below: math.huge - 1 = math.huge - return add(delay, function(f) + return self:add(delay, function(f) if func(func) == false then return end count = count - 1 if count > 0 then - add(delay, f) + self:add(delay, f) end end) end -local function cancel(func) - functions[func] = nil +function Timer:cancel(func) + self.functions[func] = nil end -local function clear() - functions = {} +function Timer:clear() + self.functions = {} end local function Interpolator(length, func) @@ -82,13 +88,17 @@ local function Oscillator(length, func) end end +-- default timer +local default = new() + -- the module -return { - update = update, - add = add, - addPeriodic = addPeriodic, - cancel = cancel, - clear = clear, +return setmetatable({ + new = new, + update = function(...) return default:update(...) end, + add = function(...) return default:add(...) end, + addPeriodic = function(...) return default:addPeriodic(...) end, + cancel = function(...) return default:cancel(...) end, + clear = function(...) return default:clear(...) end, Interpolator = Interpolator, Oscillator = Oscillator -} +}, {__call = new})