Regarding your timer lib: you can't store the index of a timer, because when you use table.remove all of the existing indexes shift over.
Also, you don't need "self:" when you are working with closures.
This is untested but it might give you a few ideas:
Code: Select all
local dim4 = {}
local timers = {}
function dim4.newTimer(isclock, delay, func, ...)
local running = false
local elapsed = 0
local t = {}
function t.update(dt)
elapsed = elapsed + dt
if elapsed < delay then
return true
end
t.callback()
if isclock then
elapsed = elapsed%delay
end
return isclock
end
function t.callback()
func(elapsed, ...)
end
function t.start()
if running then
running = true
table.insert(timers, t)
end
end
function t.stop(index)
if running then
running = false
if not index then
for i = 1, #timers do
if timers[i] == t then
index = i
break
end
end
end
assert(t == timers[index])
table.remove(timers, index)
end
end
function t.reset()
elapsed = 0
end
function t.destroy()
t.stop()
func = nil
elapsed = nil
end
return t
end
function dim4.update(dt)
for i = #timers, 1, -1 do
local t = timers[i]
if not t.update(dt) then
t.stop(i)
end
end
end
return dim4
Note that in "destroy" we unset the important "func" reference and the "elapsed" variable - this ensures that your timer cannot be used after calling "destroy".
One of the benefits of closures is that you have access to the original up-values so you can pass additional arguments:
Code: Select all
local dim4 = require("path.to.dim4")
function trigger(actualtime, p)
print(actualtime, p)
end
dim4.newTimer(true, 1, trigger, "every second!")
dim4.newTimer(false, 5, trigger, "once after five seconds")
function love.update(dt)
dim4.update(dt)
end