As a smaller example:
local function test(x)
print("Sleeping for "..x)
sleep(x)
print("Slept for "..x)
end
local cr1 = coroutine.wrap(test)
cr1(5)
when I run something like this it will print "Sleeping for 5" and then the program ends..
Generally, all your CraftOS environment is a big coroutine (or a stack of coroutines inside each other). If you call coroutine.yield(), CraftOS interprets it as an instruction to pull an event. All function that is desiged to wait for something, use this system.
os.sleep() registers a timer and calls os.pullEvent("timer").
os.pullEvent() calls os.pullEventRaw() several times until it returns "timer" event.
os.pullEventRaw() just calls coroutine.yield().
If you use your own coroutines (maybe coroutine stack), then you have to transfer control all the way up to system-controlled level, and after this you need to transfer event information all the way down to pullEvent(), which will recognise timer event and send it to sleep(), which will recognise its own timer and return to your coroutine.
local function test(x)
print("Sleeping for "..x)
sleep(x)
print("Slept for "..x)
end
local cr1 = coroutine.create(test)
local args = {5}
while coroutine.status(cr1) ~= "dead" do
local info = { coroutine.resume(cr1, unpack(args)) } -- info table may contain some information about what event to expect
if coroutine.status(cr1) ~= "dead" the
args = { coroutine.yield(unpack(info)) } -- send information to the upper level and receive a response
end
end
This is complicated, but Parallel API does it for you. As long as all your coroutine-related work is done using Parallel API, it all works fine. What parallel function does, is it creates a coroutine for each of its arguments, runs all of them until each of them requests an event, then pulls an event from the upper levels (which can be managed by parallel function too) and tells all its coroutines about that event. This process is repeated until the coroutines "die".
You don't need to worry about using this API, as long as you understand what happens inside. This API is just a part of CraftOS, like any other, and it's designed to easily operate other parts of the OS. Lua itself has nothing to do with coroutine-stack-based architecture, but I think this architecture is great!