-
Notifications
You must be signed in to change notification settings - Fork 1
/
coroprocessor.tl
75 lines (66 loc) · 1.92 KB
/
coroprocessor.tl
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
local resume = coroutine.resume
--[[
-- TODO примеры применения и зачем нужно
--]]
global type CoroProcessor = record
coros: {string:{thread}}
messages: {string:{string}}
new: function(): CoroProcessor
sendMessage: function(queuename: string, message: string)
push: function(queuename: string, func: function, ...: any)
update: function()
end
local CoroProcessor_mt: metatable<CoroProcessor> = {
__index = CoroProcessor
}
function CoroProcessor.new(): CoroProcessor
local self = setmetatable({} as CoroProcessor, CoroProcessor_mt)
self.coros = {}
self.messages = {}
return self
end
function CoroProcessor:sendMessage(queuename: string, message: string)
local tbl = self.messages[queuename]
if tbl then
table.insert(tbl, message)
end
end
function CoroProcessor:push(queuename: string, func: function, ...: any)
local q = self.coros[queuename]
if not q then
self.coros[queuename] = {}
self.messages[queuename] = {}
q = self.coros[queuename]
end
table.insert(q, coroutine.create(func))
if select("#", ...) ~= 0 then
resume(q[#q], ...)
end
end
function CoroProcessor:update()
for k, v in pairs(self.coros) do
-- Код снизу непонятен, что за индексы?
if #v >= 1 then
local msgs = self.messages[k]
local msg: string
if #msgs >= 1 then
msg = msgs[1]
table.remove(msgs, 1)
end
local ret: any
-- этот if необходим?
if msg then
ret = resume(v[1], msg)
else
ret = resume(v[1])
end
if not ret then
table.remove(v, 1)
if v[1] then
resume(v[1])
end
end
end
end
end
return CoroProcessor