如何使用 Lua C API 创建 Lua 协程?

如何使用 Lua C API 创建 Lua 协程并将其暴露给 Lua?

我正在使用 C 语言为 Lua 编写库,我想知道如何使用 Lua C API 实现 Lua 协程。我基本上想要实现像下面这样的东西,其中模块是用 C 编程语言编写的。

module = require("mymodule")

coroutine.resume(module.coroutine_function, ...)

原文链接 https://stackoverflow.com/questions/69315321

点赞
stackoverflow用户14512079
stackoverflow用户14512079

下面是 C 代码,它会输出字符串 "Wonderfull" 四次,并在协程终止前返回字符串 "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) {
    // 当运行 require("module") 时,调用此初始化函数

    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

当第一次调用 coroutine.resume 时,会调用函数 int iter(lua_State* L)。随后的调用则会调用函数 int kfunction(lua_State* L, int status, lua_KContext ctx)

lua_yieldk 的第四个参数指定了下一个 Lua 应该调用的函数来获取下一个 yield 或返回值。

文档链接:Handling Yields in C

2021-09-26 06:31:38