-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathTimer.lua
More file actions
65 lines (53 loc) · 1.21 KB
/
Timer.lua
File metadata and controls
65 lines (53 loc) · 1.21 KB
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
--Import
local pairs = pairs
local math = math
local table = table
local Class = require "Class"
local Timer = {}
setfenv (1, Timer)
local Event = Class{
elapsed = 0,
duration = 0,
callback = nil
}
Timer = Class{
nextHandle = 1
}
function Timer:getNewHandle()
if #self.freeHandles > 0 then
return table.remove(self.freeHandles)
else
local handle = self.nextHandle
self.nextHandle = self.nextHandle + 1
return handle
end
end
function Timer:init()
self.eventList = {}
self.TimerId = 1
self.freeHandles = {}
end
function Timer:start(frameDuration, callback)
local e = Event()
e.frameDuration = frameDuration
e.callback = callback
e.handle = self:getNewHandle()
self.eventList[e.handle] = e
return e.handle
end
function Timer:clear(handle)
if self.eventList[handle] then
table.insert(self.freeHandles, handle)
self.eventList[handle] = nil
end
end
function Timer:update(dt)
for handle, event in pairs(self.eventList) do
if event.elapsed >= event.frameDuration then
event.callback()
self:clear(handle)
end
event.elapsed = event.elapsed + dt
end
end
return Timer