ZNZNCOOP

Thread

Jan 5th, 2015
682
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. local mainThread=coroutine.running()
  2. local filter={}
  3.  
  4. local function SingleThread( _sFilter )
  5.     return coroutine.yield( _sFilter )
  6. end
  7.  
  8. local function MultiThread( _sFilter )
  9.   if coroutine.running()==mainThread then
  10.     local event,co
  11.     repeat
  12.       event={coroutine.yield()}
  13.       co=next(filter)
  14.       if not co then os.pullEventRaw=SingleThread end
  15.       while co do
  16.         if coroutine.status( co ) == "dead" then
  17.           filter[co],co=nil,next(filter,co)
  18.         else
  19.           if filter[co] == '' or filter[co] == event[1] or event[1] == "terminate" then
  20.             local ok, param = coroutine.resume( co, unpack(event) )
  21.             if not ok then filter={} error( param )
  22.             else filter[co] = param or '' end
  23.           end
  24.           co=next(filter,co)
  25.         end
  26.       end
  27.     until _sFilter == nil or _sFilter == event[1] or event[1] == "terminate"
  28.     return unpack(event)
  29.   else
  30.     return coroutine.yield( _sFilter )
  31.   end
  32. end
  33.  
  34. function create(f,...)
  35.   os.pullEventRaw=MultiThread
  36.   local co=coroutine.create(f)
  37.   filter[co]=''
  38.   local ok, param = coroutine.resume( co, ... )
  39.   if not ok then filter={} error( param )
  40.   else filter[co] = param or '' end
  41.   return co
  42. end
  43.  
  44. function kill(co)
  45.   filter[co]=nil
  46. end
  47.  
  48. function killAll()
  49.   filter={}
  50.   os.pullEventRaw=SingleThread
  51. end
RAW Paste Data