-
Notifications
You must be signed in to change notification settings - Fork 14
/
Copy pathtimers.lua
66 lines (58 loc) · 1.32 KB
/
timers.lua
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
-- creates and runs timers
-- also supports pausing and resuming
-- full info: http://www.lexaloffle.com/bbs/?tid=3202
-- Contributors: BenWiley4000
local timers = {}
local last_time = nil
function init_timers ()
last_time = time()
end
function add_timer (name,
length, step_fn, end_fn,
start_paused)
local timer = {
length=length,
elapsed=0,
active=not start_paused,
step_fn=step_fn,
end_fn=end_fn
}
timers[name] = timer
return timer
end
function update_timers ()
local t = time()
local dt = t - last_time
last_time = t
for name,timer in pairs(timers) do
if timer.active then
timer.elapsed += dt
local elapsed = timer.elapsed
local length = timer.length
if elapsed < length then
if timer.step_fn then
timer.step_fn(dt,elapsed,length,timer)
end
else
timer.active = false
if timer.end_fn then
timer.end_fn(dt,elapsed,length,timer)
end
end
end
end
end
function pause_timer (name)
local timer = timers[name]
if (timer) timer.active = false
end
function resume_timer (name)
local timer = timers[name]
if (timer) timer.active = true
end
function restart_timer (name, start_paused)
local timer = timers[name]
if (not timer) return
timer.elapsed = 0
timer.active = not start_paused
end