timer.lua: Add do_for(). Remove Interpolator, Oscillator.

This commit is contained in:
Matthias Richter 2012-10-02 18:28:22 +02:00
parent 0f29310dcf
commit b02273c936

View File

@ -27,29 +27,36 @@ THE SOFTWARE.
local Timer = {}
Timer.__index = Timer
local function _nothing_() end
local function new()
return setmetatable({functions = {}}, Timer)
end
function Timer:update(dt)
local to_remove = {}
for func, delay in pairs(self.functions) do
for handle, delay in pairs(self.functions) do
delay = delay - dt
if delay <= 0 then
to_remove[#to_remove+1] = func
to_remove[#to_remove+1] = handle
end
self.functions[func] = delay
self.functions[handle] = delay
handle.func(dt, delay)
end
for _,func in ipairs(to_remove) do
self.functions[func] = nil
func(func)
for _,handle in ipairs(to_remove) do
self.functions[handle] = nil
handle.after(handle.after)
end
end
function Timer:do_for(delay, func, after)
local handle = {func = func, after = after}
self.functions[handle] = delay
return handle
end
function Timer:add(delay, func)
assert(not self.functions[func], "Function already scheduled to run.")
self.functions[func] = delay
return func
return self:do_for(delay, _nothing_, func)
end
function Timer:addPeriodic(delay, func, count)
@ -64,30 +71,14 @@ function Timer:addPeriodic(delay, func, count)
end)
end
function Timer:cancel(func)
self.functions[func] = nil
function Timer:cancel(handle)
self.functions[handle] = nil
end
function Timer:clear()
self.functions = {}
end
local function Interpolator(length, func)
local t = 0
return function(dt, ...)
t = t + dt
return t <= length and func((t-dt)/length, ...) or nil
end
end
local function Oscillator(length, func)
local t = 0
return function(dt, ...)
t = (t + dt) % length
return func(t/length, ...)
end
end
-- default timer
local default = new()
@ -95,10 +86,9 @@ local default = new()
return setmetatable({
new = new,
update = function(...) return default:update(...) end,
do_for = function(...) return default:do_for(...) end,
add = function(...) return default:add(...) end,
addPeriodic = function(...) return default:addPeriodic(...) end,
cancel = function(...) return default:cancel(...) end,
clear = function(...) return default:clear(...) end,
Interpolator = Interpolator,
Oscillator = Oscillator
}, {__call = new})