You create a coroutine by calling . Its sole argument is a function that is the main function of the coroutine. The create
function only creates a new coroutine and returns a handle to it (an object of type thread); it does not start the coroutine.
You execute a coroutine by calling coroutine.resume
. When you first call , passing as its first argument a thread returned by coroutine.create
, the coroutine starts its execution, at the first line of its main function. Extra arguments passed to are passed on to the coroutine main function. After the coroutine starts running, it runs until it terminates or yields.
A coroutine yields by calling . When a coroutine yields, the corresponding returns immediately, even if the yield happens inside nested function calls (that is, not in the main function, but in a function directly or indirectly called by the main function). In the case of a yield, coroutine.resume
also returns true, plus any values passed to . The next time you resume the same coroutine, it continues its execution from the point where it yielded, with the call to coroutine.yield
returning any extra arguments passed to .
Like coroutine.create
, the function also creates a coroutine, but instead of returning the coroutine itself, it returns a function that, when called, resumes the coroutine. Any arguments passed to this function go as extra arguments to . returns all the values returned by coroutine.resume
, except the first one (the boolean error code). Unlike , coroutine.wrap
does not catch errors; any error is propagated to the caller.
When you run it, it produces the following output:
- co-body 1 10
- foo 2
- co-body r
- main true 11 -9
- main true 10 end
- main false cannot resume dead coroutine
You can also create and manipulate coroutines through the C API: see functions , lua_resume
, and .