Guest User

Untitled

a guest
Jul 22nd, 2015
531
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. local function myFunc(myArg)
  2.         for i = 1, myArg do
  3.                 print(i)
  4.                 sleep(1)
  5.         end
  6. end
  7.  
  8. -- From bios.lua, we have the source of sleep:
  9. -- function sleep( nTime )
  10. --     local timer = os.startTimer( nTime or 0 )
  11. --     repeat
  12. --         local sEvent, param = os.pullEvent( "timer" )
  13. --     until param == timer
  14. -- end
  15.  
  16. -- ... and the source of os.pullEvent():
  17. -- function os.pullEvent( sFilter )
  18. --     local eventData = { os.pullEventRaw( sFilter ) }
  19. --     if eventData[1] == "terminate" then
  20. --         error( "Terminated", 0 )
  21. --     end
  22. --     return table.unpack( eventData )
  23. -- end
  24.  
  25. -- ... and the source of os.pullEventRaw():
  26. -- function os.pullEventRaw( sFilter )
  27. --     return coroutine.yield( sFilter )
  28. -- end
  29.  
  30. -- So, os.pullEvent( "timer" ) == coroutine.yield( "timer" ), but errors if a terminate event is returned instead.
  31. -- Now let's run myFunc as a coroutine:
  32.  
  33. -- Initialise coroutine:
  34. print("Starting coroutine!")
  35.  
  36. local myCoroutine = coroutine.create(myFunc)
  37. local ok, requestedEvent = coroutine.resume(myCoroutine, 10)  -- Being the first resume, 10 gets pushed to myArg.
  38.  
  39. -- Run coroutine to completion:
  40. while coroutine.status(myCoroutine) ~= "dead" do
  41.         print("Coroutine seems ok, and is asking for a \"" .. requestedEvent .. "\" event.")  -- With the example myFunc, "requestedEvent" will always be "timer".
  42.  
  43.         local myEvent = {os.pullEvent(requestedEvent)}
  44.         ok, requestedEvent = coroutine.resume(myCoroutine, unpack(myEvent))  -- Parameters of later resumes are returned by coroutine.yield() (and hence os.pullEvent()) within the coroutine itself.
  45. end
  46.  
  47. -- Coroutine has finished execution.
  48. if ok then
  49.         print("Coroutine has completed in a natural manner.")
  50. else
  51.         print("Coroutine errored!: " .. requestedEvent)
  52. end
RAW Paste Data