- Notifications
You must be signed in to change notification settings - Fork 15
Expand file tree
/
Copy pathtimer.lua
More file actions
Latest commit
101 lines (87 loc) · 2.17 KB
/
Copy pathtimer.lua
File metadata and controls
101 lines (87 loc) · 2.17 KB
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
localtimers= {}
localtbinsert=table.insert
localtbremove=table.remove
localipairs=ipairs
localxpcall=xpcall
localtraceback=debug.traceback
localco_create=coroutine.create
localco_running=coroutine.running
localco_resume=coroutine.resume
localco_yield=coroutine.yield
---you can replace this with your clock function
localclock=os.clock
localfunctioninsert_timer(sec, fn)
localexpiretime=clock() +sec
localpos=1
fori, vinipairs(timers) do
ifv.expiretime>expiretimethen
break
end
pos=i+1
end
localcontext= { expiretime=expiretime, fn=fn}
tbinsert(timers, pos, context)
returncontext
end
localco_pool=setmetatable({}, {__mode="kv"})
localfunctioncoresume(co, ...)
localok, err=co_resume(co, ...)
ifnotokthen
error(traceback(co, err))
end
returnok, err
end
localfunctionroutine(fn)
localco=co_running()
whiletruedo
fn()
co_pool[#co_pool+1] =co
fn=co_yield()
end
end
localM= {}
functionM.async(fn)
localco=tbremove(co_pool)
ifnotcothen
co=co_create(routine)
end
local_, res=coresume(co, fn)
ifresthen
returnres
end
returnco
end
---@paramsecondsinteger @duration in seconds,decimal part means millseconds
---@paramfnfunction @ timeout callback
functionM.timeout(seconds, fn)
returninsert_timer(seconds, fn)
end
---coroutine style
---@paramsecondsinteger @duration in seconds,decimal part means millseconds
functionM.sleep(seconds)
localco=co_running()
insert_timer(seconds, function()
co_resume(co)
end)
returnco_yield()
end
functionM.remove(ctx)
ctx.remove=true
end
functionM.update()
while#timers>0do
localtimer=timers[1]
iftimer.expiretime<=clock() then
tbremove(timers,1)
ifnottimer.removethen
localok, err=xpcall(timer.fn, traceback)
ifnotokthen
print("timer error:", err)
end
end
else
break
end
end
end
returnM