Using coroutine with C++
Do not use Lua coroutine
with C++ if you have an alternative. As the iterator example showed, you can wrap coroutine
in a normal function and keep calling it until it returns nil.
But to be less opinionated and for completeness, we can use the following Lua library function to start or resume a coroutine from C++:
int lua_resume (lua_State *L, lua_State *from, int narg, int *nresults);
The function is similar to pcall
. It expects the function to be called and, optionally, its arguments on the stack. The function will be the coroutine. L
is a stack for the coroutine. from
is the stack from which the coroutine is called. narg
is the number of arguments to the coroutine
function. nresults
points to an integer and Lua will output the number of values yielded or returned to the integer.
Let’s see an example to understand how this works. In LuaExecutor...