This function pushes the thread on the stack and returns a pointer to a that represents this new thread. The new state returned by this function shares with the original state all global objects (such as tables), but has an independent run-time stack.
Each thread has an independent global environment table. When you create a thread, this table is the same as that of the given state, but you can change each one independently.
To manipulate threads as coroutines, Lua offers the following functions:
To start a coroutine, you first create a new thread; then you push on its stack the body function plus any eventual arguments; then you call lua_resume
, with narg
being the number of arguments. This call returns when the coroutine suspends or finishes its execution. When it returns, the stack contains all values passed to lua_yield
, or all values returned by the body function. lua_resume
returns 0 if there are no errors running the coroutine, or an error code (see ). In case of errors, the stack contains only the error message. To restart a coroutine, you put on its stack only the values to be passed as results from , and then call lua_resume
.
When a C function calls lua_yield
in that way, the running coroutine suspends its execution, and the call to lua_resume
that started this coroutine returns. The parameter is the number of values from the stack that are passed as results to lua_resume
.
To exchange values between different threads, you may use lua_xmove
: