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
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
-----------------------------
-- BETTER TIMER BY WEBNULL --
-- ITS OPEN-SOURCE CODE --
-----------------------------
function array(m)
local array = {}
for i = 1, m do
array[i] = 0
end
return array
end
function miliseconds()
	return tonumber(string.format("%.4f", os.clock()))
end
-- maximum limit of timer
bt_timer={}
bt={0}
function bt.push(time,func,rep)
	-- only number format in miliseconds
	if (type(time) == "number")
	then
		eoft=table.getn(bt_timer) -- check last index
		nextindex=(eoft+1) -- get id of next index
		os_time=string.format("%.4f", os.clock())
		-- initialize array
		bt_timer[nextindex]={'time','func','rep', 'r_time'}
		bt_timer[nextindex]['time']=tonumber(os_time+((time/1000)/2.1))
		bt_timer[nextindex]['time']=tonumber(os_time+((time/1000)/2.1))
		bt_timer[nextindex]['r_time']=tonumber((time/1000)/2.1)
		bt_timer[nextindex]['func']=func
		bt_timer[nextindex]['rep']=rep
		local f = io.open("sys/lua/tmp/"..nextindex..".lua", 'w')
		f:write("-- BT-Timer by WebNuLL\n")
		f:write(func)
		io.close(f)
		-- return id number
		return nextindex
	else
		-- ohh, the time argument is not a number!
		return false
	end
end
function bt.remove(id)
	if (bt_timer[id])
	then
		table.remove(bt_timer,id)
		-- removed
		return true
	else
		-- already removed
		return true
	end
		
end
function bt.init(mode)
	if (mode=="ms100") then
		addhook("ms100","bt.watch")
	elseif (mode=="second") then
		addhook("secound", "bt.watch")
	elseif (mode=="minute") then
		addhook("minute", "bt.watch")
	elseif (mode=="always") then
		addhook("always", "bt.watch")
		print("Warning the bt-timer is set to \"always\" and it can cost more CPU power.")
	end
end
function bt.watch()
	os_time=miliseconds()
	for i=0, table.getn(bt_timer) do
		if(type(bt_timer[i])=="table")
		then
			
		if(bt_timer[i]['time'] and bt_timer[i]['rep'] and bt_timer[i]['r_time'])
		then
			--msg(bt_timer[i]['time'].." - "..os_time)
			if(bt_timer[i]['time']<os_time or bt_timer[i]['time']==os_time)
			then			
				print("Executing sys/lua/tmp/"..i..".lua")	
				dofile("sys/lua/tmp/"..i..".lua")
				if(bt_timer[i]['rep']>1)
				then
					bt_timer[i]['rep']=(bt_timer[i]['rep']-1)
					bt_timer[i]['time']=(os_time+bt_timer[i]['r_time'])
				else
					-- if it only repeat 1 time, just delete it
					bt.remove(i)
				end
			end
		end
		end
	end
end
-- EXAMPLE OF USAGE!
--bt.init("ms100") -- ms100, second, minute, always is a refresh rate
--bt.push(10000,"msg(\"it works!\")",1)