【问题标题】:How to create lua coroutines using the lua c api?如何使用 lua c api 创建 lua 协程?
【发布时间】:2021-09-24 12:48:56
【问题描述】:

如何使用lua c api创建lua协程并暴露给lua?

我正在为 lua 编写一个 c 库,我想知道如何使用 lua c api 实现 lua 协程。我基本上想实现类似以下的东西,其中模块是用 c 编程语言编写的。

module = require("mymodule")

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

【问题讨论】:

  • 在 C 中,您使用 lua_newthread 创建一个新线程,然后恢复其中的任何函数。请参阅 Lua 源代码中的 lcorolib.c
  • @lhf 我已经通过lcorolib.c,但我仍然有一些问题。我的协程函数看起来像这样 ``` int coroutine(lua_State* L) { lua_pushfstring(L, "Wonderfull");返回 lua_yield(L, 1); }``` 并且多次恢复函数不会返回字符串“wonderfull”。我希望协程继续产生字符串“Wonderfull”。像这样的东西``` function iter() while true do coroutine.yield("Wonderfull") end end```

标签: c api lua


【解决方案1】:

以下是 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)

lua_yieldk 的第四个参数可以作为 Lua 应该调用的下一个函数来获取下一个产量或返回值。

文档:Handling Yields in C

【讨论】:

    猜你喜欢
    • 2021-02-25
    • 2012-07-14
    • 2010-12-10
    • 2011-11-04
    • 1970-01-01
    • 1970-01-01
    • 2020-02-05
    • 2016-10-18
    • 2018-03-22
    相关资源
    最近更新 更多