How to create lua coroutines using lua c api and expose it to lua?
I am writing a library in c for lua, And I was wondering how to implement lua coroutine using lua c api. I basically want to implement something like the following, where module is written in c programming language.
module = require("mymodule")
coroutine.resume(module.coroutine_function, ...)
CodePudding user response:
The following is C code yields the string "Wonderfull" 4 times. And returns the string "End" before terminating the coroutine.
static int kfunction(lua_State* L, int status, lua_KContext ctx)
{
static int x = 0;
if (x < 3)
{
x ;
lua_pushfstring(L, "Wonderfull");
return lua_yieldk(L, 1, 0, kfunction);
}
lua_pushfstring(L, "End");
return 1;
}
static int iter(lua_State* L)
{
lua_pushfstring(L, "Wonderfull");
return lua_yieldk(L, 1, 0, kfunction);
}
int luaopen_module(lua_State* L) {
// initial function which is called when require("module") is run
lua_State* n = lua_newthread(L);
lua_setglobal(L, "coroutine_function");
lua_pushcfunction(n, iter);
return 0;
}
Using the C module in Lua:
require("module")
print(coroutine.resume(coroutine_function)) -- true Wonderfull
print(coroutine.resume(coroutine_function)) -- true Wonderfull
print(coroutine.resume(coroutine_function)) -- true Wonderfull
print(coroutine.resume(coroutine_function)) -- true Wonderfull
print(coroutine.resume(coroutine_function)) -- true End
print(coroutine.resume(coroutine_function)) -- false cannot resume dead coroutine
int iter(lua_State* L)
is called when coroutine.resume
is called for the first time. The subsequent calls are to int kfunction(lua_State* L, int status, lua_KContext ctx)
.
4th argument to lua_yieldk
can be thorugh as the next function Lua should call to get the next yield or return value.
Documentation: Handling Yields in C