Lua/Luajit:暂停当前 Lua 线程

Lua/Luajit: pause current Lua thread

本文关键字:Lua 线程 Luajit 暂停      更新时间:2023-10-16

我目前正在使用Luajit和Lua 5.1,目前正在尝试在Lua C API中注册一个名为"Wait"的函数。该函数的主要目的是暂停当前线程。

用法示例:

print("Working");
Wait()
print("A");

但是,该函数无法按预期工作。这是我的C++代码。

#include <iostream>
#include <Windows.h>
extern "C" {
#include "Luajit/luajit.h"
#include <Luajit/lua.h>
#include <Luajit/lualib.h>
#include <Luajit/lauxlib.h>
}

static int wait(lua_State* lua) {
return lua_yield(lua, 0);
}
int main() {
lua_State* lua = luaL_newstate();
if (!lua) {
std::cout << "Failed to create Lua state" << std::endl;
system("PAUSE");
return -1;
}
luaL_openlibs(lua);
lua_register(lua, "Wait", wait);
lua_State* thread = lua_newthread(lua);
if (!thread) {
std::cout << "Failed to create Lua thread" << std::endl;
system("PAUSE");
return -1;
}
int status = luaL_loadfile(thread, "Z:/Projects/Visual Studio/Examples/Lua/Debug/Main.lua");
if (status == LUA_ERRFILE) {
std::cout << "Failed to load file" << std::endl;
system("PAUSE");
return -1;
}
int error = lua_pcall(thread, 0, 0, 0);
if (error) {
std::cout << "Error: " << lua_tostring(thread, 1) << std::endl;
}
system("PAUSE");
return 0;
}

当我加载上面发布的Lua脚本时,我得到以下输出:

Working
Error: attempt to yield across C-call boundary
Press any key to continue . . .

我已经在Lua编程超过4年了。我最近才开始使用 C API,以前从未见过 C 调用边界错误。我做了一些谷歌搜索并询问朋友,似乎没有人能帮助我。知道我的代码有什么问题吗?

当我在C++中调用 lua_yield(lua, 0) 函数时发生错误。

我尝试了以下问题的答案,但似乎没有任何效果。

http://stackoverflow.com/questions/8459459/lua-coroutine-error-tempt-to-yield-across-metamethod-c-call-boundary

lua_pcall不会启动可生成的协程。启动协程的正确函数是lua_resume