目前我正在尝试将 Lua 脚本与主机 C++ 应用程序链接起来。对于我的 Lua 脚本,我所拥有的是:
io.write(string.format("From Lua."));
我为此使用 Qt creator 并尝试像这样调用脚本:
lua_State *state = luaL_newstate();
lua_call(state , 0 , 0);
它一直给我一个 PANIC: unprotected error in call to Lua API (attempt to call a string value)
错误。
我试过将脚本包装在这样的函数中:
function main()
io.write(string.format("From Lua.With Progress"));
end
然后使用与之前相同的代码调用它,但添加了:
lua_getglobal(state , "main");
lua_pcall(state , 0 , 0 , 0);
没有错误但是:
lua_call(state , 0 , 0)
给出 PANIC: unprotected error in call to Lua API (attempt to call a nil value)
错误。
经过更多的故障排除后,我发现 luaL_loadfile(state , "EngineRxer.lua")
返回值 7 而不是 0,所以我假设脚本首先加载失败。
我还在 Qt Creator projects -> Build and run ->run 中检查了我的运行工作目录,它们与 Lua 脚本位于同一目录中。
我提到了:
Qt with Lua | Where to place lua file(s)
甚至一些 Qt 论坛:
http://www.qtcentre.org/threads/60693-Can-not-use-Lua-in-QtCreator
http://www.qtcentre.org/threads/62772-Lua-into-Qt
此外,提及我的 .pro 文件的样子可能很重要,所有 Lua 库和包含的文件都已经在那里:
LIBS += \
/usr/local/Cellar/lua/5.3.4_3/lib/liblua.5.3.4.dylib
INCLUDEPATH += \
/usr/local/Cellar/lua/5.3.4_3/include
更重要的是,经过更多故障排除后,我决定在 Netbeans(NonQt 只是 CML)上创建一个虚拟测试项目,它运行并运行良好。即使我尝试制作一个假人 fstream
程序写入一个空的 .txt 文件,它不知道在哪里可以找到它。所以我怀疑这是 Qt Creator 的问题,但我的所有路径和构建目录都指向 CWD。p>
最佳答案
以下代码片段对我有用:
int main(int argc, char** argv)
{
lua_State* L = luaL_newstate();
luaL_openlibs(L);
const char* script = "io.write(\"From Lua\")"; // or read the string from a user, file, etc.
if(luaL_loadstring(L, script) || lua_pcall(L, 0, 0, 0))
{
//error occured
const char* s = luaL_checkstring(L, -1);
fprintf(stderr, "Error in script: %s", s);
exit(EXIT_FAILURE);
}
lua_close(L);
exit(EXIT_SUCCESS);
}
你记得调用 luaL_openlibs
并加载你的脚本吗?
记得检查 lua_load*
和 lua_pcall
的返回值。他们将在堆栈顶部放置一条错误消息,您可以阅读并显示给用户。
另请参阅 luaL_loadfile 的文档:
This function returns the same results as lua_load, but it has an extra error code LUA_ERRFILE if it cannot open/read the file.
查看 lauxlib.h
header (对于 lua 5.3),我们看到 LUA_ERRFILE
等于 LUA_ERRERR+1
,即在 lua.h
中定义为 6。因此 LUA_ERRFILE
等于 7(在 Lua 5.3 中;其他版本可能有所不同)。
因此看起来您没有正确指定文件名,或者脚本不可读。尝试使用 QFile 或 std::ifstream 打开文件并将其打印到控制台以确保您正确指定了路径。
关于c++ - 在 Qt Creator 中将 Lua 与 C++ 链接起来,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50110024/