一周前我用 LuaBridge 做了第一次小测试,它成功地从脚本中获取了一个 int。
现在我删除了这段代码并尝试在我的游戏引擎中包含 Lua 脚本,但它不再有效。 我试着用这个回到基本代码:
#include <iostream>
#include "lua5.2/lua.hpp"
#include "LuaBridge/LuaBridge.h"
using namespace luabridge;
int main()
{
lua_State* L;
L = luaL_newstate();
if(!luaL_loadfile(L, "../../script.lua"))
std::cout << "failed loading" << std::endl;
LuaRef s = getGlobal(L, "nmbr");
int luaInt = s.cast<int>();
std::cout << luaInt << std::endl;
return 0;
}
用这个脚本
nmbr = 30
它给了我:
PANIC: unprotected error in cell to Lua API (bad argument #2 (number expected, got nil)) Aborted (core dumped)
当我试图从脚本中获取字符串或函数时也是如此,但我不知道我在这方面做错了什么。
感谢您的回答:)
最佳答案
来自 luaL_loadfileex
的文档:
As lua_load, this function only loads the chunk; it does not run it.
这意味着脚本已加载,但尚未执行,因此实际上没有可获取的变量 nmbr
。您需要先运行脚本才能使代码正常工作(例如调用 lua_call
)。
这在第一个简单示例中得到了很好的展示 in this LuaBridge tutorial .
关于c++ - LuaBridge getGlobal 总是返回 nil,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32223334/