尝试通过协程使用lua_sethook在Lua API中实现多线程

大家好,请帮帮我。我尝试通过协程使用lua_sethook在Lua API中实现多线程。

以下是代码

void LUAHook(lua_State* L, lua_Debug* ar) {
    lua_yield(L, 0);
};
 const char* LUA = R"(
function foo()
for i = 1, 4 do
print(" func foo \n")
end end

function main()
for i = 1, 3 do
print(" func main "..i.."\n")
if j == nil
then
 foo1()
j=1
end
end  end
)";
int foo1(lua_State* L) {
    lua_State* L1 = lua_newthread(L);
    lua_sethook(L, LUAHook, LUA_MASKLINE, 1);
    lua_getglobal(L1, "foo");
    lua_sethook(L1, LUAHook, LUA_MASKLINE, 1);
    lua_resume(L1, L, 0);

return  0;
};
int main() {
    lua_State* L = luaL_newstate(); luaL_openlibs(L);
    lua_register(L, "foo1", foo1);
    luaL_dostring(L, LUA);
    int ret;
    lua_getglobal(L, "main");// 函数从上一次中断的位置恢复。
    ret = lua_resume(L, NULL, 0);

    return 0;
};

您需要在控制台中显示以下内容

func main 1 func foo func main 2 func foo func main 3 func foo enter code here

点赞