Debian Codegraph @

lua/include/timer.lua

raw symbols SCIP
1 --[[
2 Copyright (C) 2014 HarpyWar ([email protected])
3
4 This file is a part of the PvPGN Project http://pvpgn.pro
5 Licensed under the same terms as Lua itself.
6 ]]--
7
8
9 -- Global table with timers
10 __timers = {}
11
12 function timer_add(id, interval, callback)
13 timer_object = timer:new(id, interval, callback)
14 table.insert(__timers, timer_object)
15 end
16
17 function timer_del(id)
18 -- safe remove from the timers (we can not just use __timers = nil here)
19 local i = 0
20 for k,v in pairs(__timers) do
21 i = i + 1
22 if (v.id == id) then
23 table.remove(__timers, i)
24 return true
25 end
26 end
27 return false
28 end
29
30 function timer_get(id)
31 local i = 0
32 for k,v in pairs(__timers) do
33 i = i + 1
34 if (v.id == id) then
35 return v
36 end
37 end
38 end
39
40
41 --
42 -- Timer class
43 --
44 timer = {}
45
46 -- Create a new timer with unique id and given interval
47 function timer:new(id, interval, callback)
48 options = { id = id, interval = interval, prev_time = 0, callback = callback }
49 self.__index = self
50 return setmetatable(options, self)
51 end
52
53 -- Event when timer executes
54 function timer:tick()
55 if os.time() < self.prev_time + self.interval then return 0 end
56 self.prev_time = os.time()
57
58 -- Debug: display time when the timer ticks
59 -- TRACE(self.interval .. ": " .. os.time())
60
61 -- execute callback function
62 return self.callback(self)
63 end
64
65