-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Showing
6 changed files
with
230 additions
and
73 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,70 @@ | ||
local resume = coroutine.resume | ||
|
||
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 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 | ||
|
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.