Advertisement
Guest User

dispatcher

a guest
Apr 1st, 2015
181
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Lua 2.31 KB | None | 0 0
  1. --this file is an API for dynamically adding coroutines to the running set
  2. local dbg = true
  3. local routines = {}
  4.  
  5. function setDebug(b) if type(b) ~= "boolean" then error("Expected boolean",2) end dbg = b return end
  6.  
  7. function add(f,...) --add coro that starts at f(...)
  8.   if (type(f) ~= "function") then error("Expected function",2) return  end
  9.   local coro = coroutine.create(f)
  10.   routines[coro] = {func=f,args={...},started=false,filter=nil,persistent=false}
  11.   return
  12. end
  13.  
  14. function addPersistent(f,...) --as add, but dispatcher revives coro when it dies
  15.   if (type(f) ~= "function") then error("Expected function",2) return  end
  16.   local coro = coroutine.create(f)
  17.   routines[coro] = {func=f,args={...},started=false,filter=nil,persistent=true,}
  18.   return
  19. end
  20.  
  21. function begin(f,...) --main body of dispatcher
  22.   if (f ~= nil) then
  23.     if (type(f) ~= "function") then error("Expected function",2) return  end
  24.     add(f,...)
  25.   end
  26.  
  27.   local event = {}
  28.   while true do
  29.     local mfd = {}
  30.     for coro,t in pairs(routines) do
  31.       if (coro ~= nil) then
  32.         if (t.started == false) then
  33.           t.started = true
  34.           local _,param = coroutine.resume(coro,unpack(t.args))
  35.           t.filter = param
  36.           if (dbg) then print("thread returned: ",coro) for _,v in pairs({param}) do write("  ") print(v) end end
  37.         else
  38.           if ((t.filter == nil) or (t.filter == event[1]) or (event[1] == "terminate")) then
  39.              if (dbg) then print("resuming thread: ",coro) end
  40.              local _,param = coroutine.resume(coro,unpack(event))
  41.              t.filter = param
  42.              if (dbg) then print("thread returned: ",coro) for _,v in pairs({param}) do write("  ") print(v) end end
  43.           end
  44.         end
  45.         if (coroutine.status(coro) == "dead") then
  46.           if (dbg) then print("thread died: ",coro) end
  47.           if (t.persistent == true) then --revive persistent coroutine with same args
  48.             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
  49.             addPersistent(t.func,unpack(t.args))
  50.           end
  51.           table.insert(mfd,coro)
  52.         end
  53.       end
  54.     end
  55.     for _,coro in pairs(mfd) do routines[coro] = nil end
  56.     event = {os.pullEvent()}
  57.   end
  58. end
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement