diff options
Diffstat (limited to 'bin/timer/timer.lua')
-rw-r--r-- | bin/timer/timer.lua | 78 |
1 files changed, 78 insertions, 0 deletions
diff --git a/bin/timer/timer.lua b/bin/timer/timer.lua new file mode 100644 index 0000000..398f47f --- /dev/null +++ b/bin/timer/timer.lua @@ -0,0 +1,78 @@ +local Timer = {} +local MODE = { + NONE = 0, + EVERY = 1, + REPEATS = 2, + AFTER = 3, +} +Timer.timers = {} +local timer = { + new = function(self, _mod, _duration, _count, _callback) + local t = {} + setmetatable(t, self) + self.__index = self + t:_init(_mod, _duration, _count, _callback) + return t + end, + _init = function(self, _mod, _duration, _count, _callback) + self.tick = 0 + self.duration = _duration + self.mode = _mod + self.count = _count + self.callback = _callback + end, + update = function(self, dt) + self.tick = self.tick + dt + if self.tick >= self.duration then + if self.mode == MODE.EVERY then + self.tick = 0 + elseif self.mode == MODE.REPEATS then + self.tick = 0 + self.count = self.count - 1 + if self.count <= 0 then + -- remove this + for i, v in ipairs(Timer.timers) do + if v == self then + table.remove(Timer.timers, i) + break + end + end + end + elseif self.mode == MODE.AFTER then + -- remove this + for i, v in ipairs(Timer.timers) do + if v == self then + table.remove(Timer.timers, i) + break + end + end + end + if self.callback then + self.callback() + end + end + end +} + +Timer.update = function(sec) + for _, t in ipairs(Timer.timers) do + t:update(sec) + end +end + +Timer.every = function(sec, callback) + local t = timer:new(MODE.EVERY, sec, nil, callback) + table.insert(Timer.timers, t) +end + +Timer.repeats = function(sec, rpt, callback) + local t = timer:new(MODE.REPEATS, sec, rpt, callback) + table.insert(Timer.timers, t) +end + +Timer.after = function(sec, callback) + local t = timer:new(MODE.AFTER, sec, nil, callback) + table.insert(Timer.timers, t) +end + +return Timer
\ No newline at end of file |