I try to implement multithreading in Lua Api through coroutines using lua_sethook.
here's the code
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");// функция lua возобновляется с последней
// прерванной позиции.
ret = lua_resume(L, NULL, 0);
return 0;
};
me need to display the following in the console
func main 1
func foo
func main 2
func foo
func main 3
func foo