T
T is a PICO-8 library for scheduled and/or periodic function invocation.
Code
t_queue = {}
-- add an action to be executed at t()+secs, e.g.,
-- t_at(t()+1, set_kv, {pos, "x", 64})
-- optional: append an id to make the action
-- cancellable via t_cancel(id)
function t_at(secs, fn, arg, _id)
add(t_queue, {t=secs, f=fn, arg=arg, id=_id})
end
-- add an action to be executed in n secs, e.g.,
-- t_in(1, set_kv, {pos, "x", 64})
-- optional: append an id to make the action
-- cancellable via t_cancel(id)
function t_in(secs, fn, arg, _id)
t_at(t()+secs, fn, arg, _id)
end
-- add an action that repeats every secs, e.g.,
-- every(1, sfx, 1) => calls sfx(1) every second
-- optional: append an id to make the action
-- cancellable via q_cancel(id)
function t_every(secs, fn, arg, _id)
add(t_queue, {
t=time()+secs,
f=fn,
arg=arg,
rep=true,
interval=secs,
id=_id
})
end
-- add this to _update function
function t_step()
for item in all(t_queue) do
if time() > item.t then
item.f(item.arg)
if item.rep then
item.t += item.interval
else
del(t_queue, item)
end
end
end
end
-- cancel an action
function t_cancel(id)
local idx
for i = 1,#t_queue do
if t_queue[i].id == id then
idx = i
break
end
end
if idx then deli(t_queue,idx) end
end
-- cancel everything
function t_clear()
t_queue = {}
end
-- commmon actions
-- set_kv({tbl, key, value})
-- e.g.,
-- t_in(1, set_kv, {entity, "color", 8})
function set_kv(params)
local tbl, key, val = unpack(params)
tbl[key] = val
end
-- set_upd(my_update)
-- e.g.,
-- t_in(1, set_upd, my_update)
function set_upd(f)
_update = f
end
-- set_drw(my_draw)
-- e.g.,
-- t_in(1, set_drw, my_draw)
function set_drw(f)
_draw = f
end