Can lua_status detect if a function yields after being called using lua_call?

Viewed 143

this is my first question on this forum so please excuse me if I don't do this correct. I am currently working on a little project in C++ which uses the Lua API and I am trying to detect yielding without using lua_resume and lua_pcall. The reason for not using these is just simply because I can't use them for this project. This is a small representation of the code I have to run the delay function I registered.

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?
}

Basically, like you can see in my code my question is the following; Will I get a return from lua_resume if lua_call yields?

1 Answers

Code ran by lua_call can't yield. For yielding to work, you'd have to use lua_callk instead. Once you do that, it'll be obvious whether the Lua code yielded: Just check the status parameter to your k function. Example:

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.
}
Related