Created
December 20, 2016 08:50
-
-
Save Jerakin/2b6aa7f59d77a20e4d146ebb49405ba4 to your computer and use it in GitHub Desktop.
Defold, Lua timer module
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
-- A timer module for Defold, supports a regular timer and a repeating timer, | |
-- timer fires its callback once, the repeating timer fire its callback until it is canceled | |
-- Locals | |
local M = {} | |
------------------------------------------------------------------------------ | |
function M.create() | |
local self = {} | |
self.timers = {} | |
return self | |
end | |
------------------------------------------------------------------------------ | |
function M.cancel_all(self) | |
for index = #self.timers, 1, -1 do | |
table.remove(self.timers, index) | |
end | |
end | |
------------------------------------------------------------------------------ | |
function M.add_timer(self, time_out, callback_func, args) | |
local timer = {} | |
timer.time_left = time_out | |
timer.callback = callback_func | |
timer.args = args | |
table.insert(self.timers, timer) | |
end | |
------------------------------------------------------------------------------ | |
function M.add_repeating_timer(self, time_out, callback_func, args) | |
local timer = {} | |
timer.time_left = time_out | |
timer.repeat_every = time_out | |
timer.callback = callback_func | |
timer.args = args | |
table.insert(self.timers, timer) | |
end | |
------------------------------------------------------------------------------ | |
function M.update(self, dt) | |
local triggered_timers = {} | |
for index = #self.timers, 1, -1 do | |
self.timers[index].time_left = self.timers[index].time_left - dt | |
if self.timers[index].time_left <= 0.0 then | |
table.insert(triggered_timers, self.timers[index]) | |
if self.timers[index].repeat_every ~= nil then | |
self.timers[index].time_left = self.timers[index].repeat_every | |
else | |
table.remove(self.timers, index) | |
end | |
end | |
end | |
for index = #triggered_timers, 1, -1 do | |
triggered_timers[index].callback(triggered_timers[index].args) | |
end | |
end | |
return M |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment