This repository has been archived by the owner on Dec 4, 2023. It is now read-only.
/
task.lua
83 lines (78 loc) · 1.71 KB
/
task.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
local rem=table.remove
local assert,resume,status=assert,coroutine.resume,coroutine.status
local rawset=rawset
local timer=love.timer.getTime
local TASK={}
-- Locks
local locks=setmetatable({},{
__index=function(self,k) rawset(self,k,-1e99)return -1e99 end,
__newindex=function(self,k) rawset(self,k,-1e99) end,
})
function TASK.lock(name,T)
if timer()>=locks[name] then
locks[name]=timer()+(T or 1e99)
return true
else
return false
end
end
function TASK.unlock(name)
locks[name]=-1e99
end
function TASK.getLock(name)
local v=locks[name]-timer()
return v>0 and v
end
function TASK.clearLock()
for k in next,locks do
locks[k]=nil
end
end
local tasks={}
function TASK.getCount()
return #tasks
end
local trigFrame=0
function TASK.update(dt)
trigFrame=trigFrame+dt*60
for _=1,trigFrame do
for i=#tasks,1,-1 do
local T=tasks[i]
if status(T.thread)=='dead' then
rem(tasks,i)
else
assert(resume(T.thread,dt/trigFrame))
end
end
end
trigFrame=1
end
function TASK.new(code,...)
local thread=coroutine.create(code)
assert(resume(thread,...))
if status(thread)~='dead' then
tasks[#tasks+1]={
thread=thread,
code=code,
args={...},
}
end
end
function TASK.removeTask_code(code)
for i=#tasks,1,-1 do
if tasks[i].code==code then
rem(tasks,i)
end
end
end
function TASK.removeTask_iterate(func,...)
for i=#tasks,1,-1 do
if func(tasks[i],...) then
rem(tasks,i)
end
end
end
function TASK.clear()
TABLE.cut(tasks)
end
return TASK