如何使用lua c api创建lua协程并将其公开给lua?
我正在用 c 为 lua 编写一个库,我想知道如何使用 lua c api 实现 lua 协程。我基本上想实现如下内容,其中模块是用 c 编程语言编写的。
module = require("mymodule")
coroutine.resume(module.coroutine_function, ...)
以下是 C 代码产生字符串 "Wonderfull" 4 次。并在终止协程之前返回字符串“End”。
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;
}
在 Lua 中使用 C 模块:
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)
coroutine.resume
第一次调用时调用。随后的调用是int kfunction(lua_State* L, int status, lua_KContext ctx)
。
第 4 个参数lua_yieldk
可以是完整的,因为 Lua 应该调用下一个函数来获取下一个产量或返回值。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句