3

这是我在这个论坛上的第一个问题,所以如果我不这样做,请原谅我。我目前正在开发一个使用 Lua API 的 C++ 小项目,我试图在不使用lua_resumelua_pcall的情况下检测屈服。不使用这些的原因仅仅是因为我不能在这个项目中使用它们。这是我必须运行我注册的延迟函数的代码的一个小表示。

void DoSleep(lua_State* L)
{
    lua_getglobal(L, "custom_delay"); // Custom function
    lua_pushnumber(L, 2); // Seconds
    lua_call(L, 1, 0); // 1 arg, no returns

    // Can I see if it yields using lua_status?
}

基本上,就像您在我的代码中看到的那样,我的问题如下;如果 lua_call 产生,我会从 lua_resume 获得回报吗?

4

1 回答 1

1

运行的代码lua_call 无法产生。为了屈服于工作,您必须lua_callk改用。一旦你这样做了,Lua 代码是否成功就很明显了:只需检查status你的k函数的参数。例子:

static void DoSleep_k(lua_State* L, int status, lua_KContext ctx)
{
    if(status == LUA_YIELD) {
        // It yielded
    } else {
        // It didn't yield
    }
}

void DoSleep(lua_State* L)
{
    lua_getglobal(L, "custom_delay"); // Custom function
    lua_pushnumber(L, 2); // Seconds
    lua_KContext ctx = 0; // If you have any C local variables you care about, squeeze them in here somehow. Otherwise, just leave it 0.
    lua_callk(L, 1, 0, ctx, DoSleep_k); // 1 arg, no returns
    DoSleep_k(L, LUA_OK, ctx);
    // Don't put any more code here! Anything you want to happen after you call back into Lua, do in DoSleep_k above instead.
}
于 2021-04-27T04:01:29.130 回答