5bitesofcookies

Untitled

May 19th, 2014
117
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.37 KB | None | 0 0
  1. local function my_function( ) -- this is just a demo function
  2. while true do
  3. local event, key = coroutine.yield( ) -- this stops the coroutine and waits for it to be resumed. It will set event, key to the arguments that it is resumed with
  4. if event == "char" then
  5. print( key )
  6. else
  7. error( "You didn't press a key!" )
  8. end
  9. end
  10. end
  11. local function my_other_function( )
  12. while true do
  13. sleep( 10000 ) -- would normally make the other function wait 10000 seconds
  14. end
  15. end
  16. local my_coroutine = coroutine.create( my_function ) -- creates a coroutine from my_function
  17. local my_other_coroutine = coroutine.create( my_other_function ) -- ditto
  18. while true do -- an infinite loop
  19. local event = { os.pullEvent("char") } -- captures the event in a table
  20. local ok, err = coroutine.resume( my_coroutine, unpack( event ) ) -- runs the coroutine with the event like [event, key, etc]
  21. coroutine.resume( my_other_coroutine) -- runs this too, and when sleep is called, it stops running because sleep->os.pullEvent->os.pullEventRaw->coroutine.yield( )
  22. if not ok then -- if the coroutine errored then...
  23. print( err ) -- print the error
  24. break -- exit from the loop
  25. end
  26. end
Advertisement
Add Comment
Please, Sign In to add comment