Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- --this file is an API for dynamically adding coroutines to the running set
- local dbg = true
- local routines = {}
- function setDebug(b) if type(b) ~= "boolean" then error("Expected boolean",2) end dbg = b return end
- function add(f,...) --add coro that starts at f(...)
- if (type(f) ~= "function") then error("Expected function",2) return end
- local coro = coroutine.create(f)
- routines[coro] = {func=f,args={...},started=false,filter=nil,persistent=false}
- return
- end
- function addPersistent(f,...) --as add, but dispatcher revives coro when it dies
- if (type(f) ~= "function") then error("Expected function",2) return end
- local coro = coroutine.create(f)
- routines[coro] = {func=f,args={...},started=false,filter=nil,persistent=true,}
- return
- end
- function begin(f,...) --main body of dispatcher
- if (f ~= nil) then
- if (type(f) ~= "function") then error("Expected function",2) return end
- add(f,...)
- end
- local event = {}
- while true do
- local mfd = {}
- for coro,t in pairs(routines) do
- if (coro ~= nil) then
- if (t.started == false) then
- t.started = true
- local _,param = coroutine.resume(coro,unpack(t.args))
- t.filter = param
- if (dbg) then print("thread returned: ",coro) for _,v in pairs({param}) do write(" ") print(v) end end
- else
- if ((t.filter == nil) or (t.filter == event[1]) or (event[1] == "terminate")) then
- if (dbg) then print("resuming thread: ",coro) end
- local _,param = coroutine.resume(coro,unpack(event))
- t.filter = param
- if (dbg) then print("thread returned: ",coro) for _,v in pairs({param}) do write(" ") print(v) end end
- end
- end
- if (coroutine.status(coro) == "dead") then
- if (dbg) then print("thread died: ",coro) end
- if (t.persistent == true) then --revive persistent coroutine with same args
- if (dbg) then print("reviving persistent thread:") write(" ") print("coro") write(" ") print(t.func) for _,v in pairs(t.args) do write(" ") print(v) end end
- addPersistent(t.func,unpack(t.args))
- end
- table.insert(mfd,coro)
- end
- end
- end
- for _,coro in pairs(mfd) do routines[coro] = nil end
- event = {os.pullEvent()}
- end
- end
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement