I'm a bit newbie in this game engine and lua and I wanted to create a game, though it made it harder for me because of the love.update() function which I have to add functions on my every single lib that needs periodic execution. Because of this I created a small library that allows you to create "timers" that periodically executes or executes delayed functions.
Code:
Code: Select all
--[[
timer.lua by Almia
a library that handles periodic or delayed execution of functions
via virtual timers.
Timers has a minimum of 32 executions per second.
--------------------------------------------
API
timer.start(timeout, doReset, handler)
- starts a timer
*timeout - how often the timer executes handlers
*doReset - does the timer executes again?
*handler - the initial handling function that
is executed every time the timer expires.
timer:pause()
- pauses the timer
timer:resume()
- resumes the timer
timer:setTimeout(timeout)
- changes/sets the timer's timeout
timer.update(dt)
- must be put inside the love.update, also having the love.update's dt
]]--
MIN_TIMEOUT = 0.031250000 -- 32 frames
timer = {}
timer.__index = timer
local timers = {}
function timer.start(timeout, doReset, handler)
if type(timeout) == "number" then
if timeout <= MIN_TIMEOUT then
timeout = MIN_TIMEOUT
end
else
timeout = MIN_TIMEOUT
end
local new = {active = true,
timeout = timeout,
doReset = doReset,
handler = handler,
prev = love.timer.getTime()}
table.insert(timers, new)
setmetatable(new, timer)
return new
end
function timer:pause()
self.active = false
end
function timer:resume()
self.active = true
end
function timer:setTimeout(timeout)
if timeout <= MIN_TIMEOUT then
timeout = MIN_TIMEOUT
end
if self.active then
self.prev = love.timer.getTime()
end
self.timeout = timeout
end
function timer.update()
dt = love.timer.getTime()
for k, t in ipairs(timers) do
if t.active then
if dt - t.prev >= t.timeout then
t.handler()
if t.doReset then
t.prev = dt
else
t.pause()
end
end
end
end
end
Code: Select all
require "timer"
function love.load()
local t = 0.031250000
text = {}
for i = 1,32 do
text[i] = 0
timer.start(t, true, function ()
text[i] = text[i] + 1
end)
t = t + MIN_TIMEOUT
end
end
function love.update()
timer.update()
end
function love.draw()
local y = 0
local yg = 600/32
for i = 1, 32 do
love.graphics.print((33 - i).." frames : "..text[i], 100, y)
y = y + yg
end
end
[edit]
Update 1.1
- Merged .start with .new
- Timers now handles only single functions
- added .resume function
- (Misc) improved demo