Advertisement
King0fGamesYami

statemachine

Jan 28th, 2016
656
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Lua 1.81 KB | None | 0 0
  1. local loop, event = nil, {} --pre-declare the loop and event
  2.  
  3. function unblock( func )
  4.     --create the coroutine
  5.     --start with the function parameters
  6.     --unblock( sleep, 1 ) will work because of this
  7.     --pre-declare filter (starts without one)
  8.     local tEventData, co, filter = {}
  9.     return function( ... ) --return a function you can call as many times as you like
  10.         if not co or coroutine.status( co ) == "dead" then --We need a fresh copy of our function
  11.             co = coroutine.create( func )
  12.             tEventData = {...}
  13.             filter = nil
  14.         end
  15.         tEventData = event or {} --get the current event from the statemachine
  16.         if not filter or tEventData[ 1 ] == filter then --if there isn't a filter or the filter matches
  17.             local tVar = {coroutine.resume( co, unpack( tEventData ) )} --we resume the coroutine
  18.             if tVar[ 1 ] and coroutine.status( co ) ~= "dead" then --if the coroutine didn't error and isn't done
  19.                 --we have a filter (or lack thereof)
  20.                 filter = tVar[ 2 ]
  21.             elseif tVar[ 1 ] then --if the coroutine didn't error but is done
  22.                 --we have a returned value, and the execution has finished
  23.                 return unpack( tVar )
  24.             elseif coroutine.status( co ) == "dead" then --if the coroutine is dead, but wasn't ok
  25.                 --we have an error
  26.                 error( tVar[ 2 ], 0 )
  27.             end
  28.         end
  29.     end
  30. end
  31.  
  32. function setLoop( func ) --sets the loop function to call
  33.     if type( func ) ~= "function" then --if you sent me a value I didn't want
  34.         error( "Expected function, got " .. type( func ), 2 ) --I'm going to tell you
  35.     end
  36.     loop = func
  37. end
  38.  
  39. function run() --this is the only blocking call of this API, literally to run the program
  40.     while true do
  41.         if loop() then
  42.             break
  43.         end
  44.         event = {os.pullEventRaw()} --this handles event handling for you
  45.     end
  46. end
  47.  
  48. function pullEvent() --my own pullEvent thing.
  49.     return unpack( event )
  50. end
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement