-
Notifications
You must be signed in to change notification settings - Fork 0
/
taskmgr.lua
90 lines (73 loc) · 2.23 KB
/
taskmgr.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
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
local globalvars = require("global_vars")
local tasks = {}
local last_task_id = 0
task = {}
local time_old = 0
local global_time = 0
function task.pause( seconds )
local time = global_time + seconds
while(true) do
if(time < global_time) then return end
coroutine.yield()
end
end
function task.remove(id)
for i,v in ipairs(tasks) do
if id == tasks[i].id then
table.remove(tasks, i)
return
end
end
end
local function task_callback(time, cb)
task.pause(time)
pcall(cb)
end
engine_callback.register("pfnStartFrame", function()
local diff = globalvars.time - time_old
time_old = globalvars.time
if diff > 0 then global_time = global_time + diff else return end
--[[print(string.format("Time now: %f\nTime diff = %f", globalvars.time, diff)) ]] --
local tasks_remove = {}
for i,v in ipairs(tasks) do
if tasks[i].repeat_count ~= 0 then
-- Resume coroutine after suspend --
if tasks[i].coroutine ~= nil then
if coroutine.status(tasks[i].coroutine) == "suspended" then
coroutine.resume(tasks[i].coroutine)
else
-- Coroutine is dead. Not big surprise. --
tasks[i].coroutine = coroutine.create(task_callback)
coroutine.resume(tasks[i].coroutine, tasks[i].time, tasks[i].cb)
if tasks[i].repeat_count ~= -1 then
tasks[i].repeat_count = tasks[i].repeat_count - 1
end
end
else
-- Coroutine not created. Not big surprise. --
tasks[i].coroutine = coroutine.create(task_callback)
coroutine.resume(tasks[i].coroutine, tasks[i].time, tasks[i].cb)
if tasks[i].repeat_count ~= -1 then
tasks[i].repeat_count = tasks[i].repeat_count - 1
end
end
else
-- mark object to remove --
table.insert(tasks_remove, tasks[i].id)
end
end
-- collect garbage --
for i,v in ipairs(tasks) do
task.remove(tasks_remove[i])
end
end)
--[[ pass -1 to repeat_count to task.add for infinite execution (if repeat == 0 task automaticaly removed)]]--
task.infinite = -1
function task.add(time, callback, repeat_count)
last_task_id = last_task_id + 1
local id = last_task_id
-- FIXME: add 1 to avoid strange bug --
if repeat_count ~= -1 then repeat_count = repeat_count + 1 end
table.insert(tasks, {id = id, time = time, cb = callback, repeat_count = repeat_count})
return id
end