Advertisement
Guest User

dispatcher

a guest
Mar 31st, 2015
232
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Lua 1.12 KB | None | 0 0
  1. --this file is an API for dynamically adding coroutines to the running set
  2. local routines = {}
  3.  
  4. function add(f,...)
  5.   if (type(f) ~= "function") then error("Expected function",2) return  end
  6.   local coro = coroutine.create(f)
  7.   routines[coro] = {args={...},started=false,filter=nil}
  8.   return
  9. end
  10.  
  11. function begin(f,...)
  12.   if (type(f) ~= "function") then error("Expected function",2) return  end
  13.   add(f,...)
  14.  
  15.   local event = {}
  16.   while true do
  17.     local mfd = {}
  18.     for coro,t in pairs(routines) do
  19.       if (coro ~= nil) then
  20.         if (t.started == false) then
  21.           t.started = true
  22.           local _,param = coroutine.resume(coro,unpack(t.args))
  23.           t.filter = param
  24.         else
  25.           if ((t.filter == nil) or (t.filter == event[1]) or (event[1] == "terminate")) then
  26.             local _,param = coroutine.resume(coro,unpack(event))
  27.             t.filter = param
  28.           end
  29.         end
  30.         if (coroutine.status(coro) == "dead") then table.insert(mfd,coro) end
  31.       end
  32.     end
  33.     for _,coro in pairs(mfd) do routines[coro] = nil end
  34.     event = {os.pullEventRaw()}
  35.   end
  36. end
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement