Bugfix: Timer.update(dt) sometimes fails on `for'

Deleting functions from the function register while looping over
it could break the next-iterator in the for loop. To prevent that
from happening, we collect the functions to be deleted and delete
them in an extra loop.
Functions will still only be called after they have been removed
from the timer register.
This commit is contained in:
Matthias Richter 2011-01-12 12:18:37 +01:00
parent 72b06e2387
commit 0dc9eacc57

View File

@ -27,15 +27,19 @@ THE SOFTWARE.
Timer = {}
Timer.functions = {}
function Timer.update(dt)
local to_remove = {}
for func, delay in pairs(Timer.functions) do
delay = delay - dt
if delay <= 0 then
Timer.functions[func] = nil
func(func)
to_remove[#to_remove+1] = func
else
Timer.functions[func] = delay
end
end
for _,func in ipairs(to_remove) do
Timer.functions[func] = nil
func(func)
end
end
function Timer.add(delay, func)