Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- local function myFunc(myArg)
- for i = 1, myArg do
- print(i)
- sleep(1)
- end
- end
- -- From bios.lua, we have the source of sleep:
- -- function sleep( nTime )
- -- local timer = os.startTimer( nTime or 0 )
- -- repeat
- -- local sEvent, param = os.pullEvent( "timer" )
- -- until param == timer
- -- end
- -- ... and the source of os.pullEvent():
- -- function os.pullEvent( sFilter )
- -- local eventData = { os.pullEventRaw( sFilter ) }
- -- if eventData[1] == "terminate" then
- -- error( "Terminated", 0 )
- -- end
- -- return table.unpack( eventData )
- -- end
- -- ... and the source of os.pullEventRaw():
- -- function os.pullEventRaw( sFilter )
- -- return coroutine.yield( sFilter )
- -- end
- -- So, os.pullEvent( "timer" ) == coroutine.yield( "timer" ), but errors if a terminate event is returned instead.
- -- Now let's run myFunc as a coroutine:
- -- Initialise coroutine:
- print("Starting coroutine!")
- local myCoroutine = coroutine.create(myFunc)
- local ok, requestedEvent = coroutine.resume(myCoroutine, 10) -- Being the first resume, 10 gets pushed to myArg.
- -- Run coroutine to completion:
- while coroutine.status(myCoroutine) ~= "dead" do
- print("Coroutine seems ok, and is asking for a \"" .. requestedEvent .. "\" event.") -- With the example myFunc, "requestedEvent" will always be "timer".
- local myEvent = {os.pullEvent(requestedEvent)}
- ok, requestedEvent = coroutine.resume(myCoroutine, unpack(myEvent)) -- Parameters of later resumes are returned by coroutine.yield() (and hence os.pullEvent()) within the coroutine itself.
- end
- -- Coroutine has finished execution.
- if ok then
- print("Coroutine has completed in a natural manner.")
- else
- print("Coroutine errored!: " .. requestedEvent)
- end
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement