summaryrefslogtreecommitdiff
path: root/timer/timer.lua
blob: 398f47f3e58e2c4f4ce1f1ddde078feee38cbd09 (plain)
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
67
68
69
70
71
72
73
74
75
76
77
78
local Timer = {} 
local MODE = {
	NONE = 0, 
	EVERY = 1, 
	REPEATS = 2, 
	AFTER = 3,
}
Timer.timers = {}
local timer = {
	new = function(self, _mod, _duration, _count, _callback) 
		local t = {} 
		setmetatable(t, self)
		self.__index = self 
		t:_init(_mod, _duration, _count, _callback)
		return t
	end,
	_init = function(self, _mod, _duration, _count, _callback)
		self.tick = 0        
		self.duration = _duration 
		self.mode = _mod 
		self.count = _count 
		self.callback = _callback
	end,
	update = function(self, dt)
		self.tick = self.tick + dt 
		if self.tick >= self.duration then 
			if self.mode == MODE.EVERY then 
				self.tick = 0 
			elseif self.mode == MODE.REPEATS then 
				self.tick = 0 
				self.count = self.count - 1
				if self.count <= 0 then 
					-- remove this 
					for i, v in ipairs(Timer.timers) do 
						if v == self then 
							table.remove(Timer.timers, i)
							break
						end 
					end 
				end 
			elseif self.mode == MODE.AFTER then 
				-- remove this 
				for i, v in ipairs(Timer.timers) do 
					if v == self then 
						table.remove(Timer.timers, i)
						break
					end 
				end 
			end 
			if self.callback then 
				self.callback()
			end 
		end 
	end 
}

Timer.update = function(sec)
	for _, t in ipairs(Timer.timers) do 
		t:update(sec)		
	end 
end 

Timer.every = function(sec, callback)
	local t = timer:new(MODE.EVERY, sec, nil, callback)
	table.insert(Timer.timers, t)
end

Timer.repeats = function(sec, rpt, callback)
	local t = timer:new(MODE.REPEATS, sec, rpt, callback)
	table.insert(Timer.timers, t)
end 

Timer.after = function(sec, callback) 
	local t = timer:new(MODE.AFTER, sec, nil, callback)
	table.insert(Timer.timers, t)
end 

return Timer