Skip to content

Instantly share code, notes, and snippets.

@Jerakin
Created December 20, 2016 08:50
Show Gist options
  • Save Jerakin/2b6aa7f59d77a20e4d146ebb49405ba4 to your computer and use it in GitHub Desktop.
Save Jerakin/2b6aa7f59d77a20e4d146ebb49405ba4 to your computer and use it in GitHub Desktop.
Defold, Lua timer module
-- 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