c++ - LuaBridge getGlobal 总是返回 nil

标签 c++ lua luabridge

一周前我用 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/

相关文章:

c++ - map 上的 find_if 问题

lua - 如何使用动态变量名称?

C++ 在 unixtime 中获取今年的开始

c++ - 通过内部颜色过滤OpenCV轮廓

redis - 来自 JSON 的 Redis 中的 Lua

lua - 如何使用 autotools 在 libdir 的子目录中安装 lua 模块

c++ - 使用 LuaBridge 或 Lua 将 C++ 对象传递给 Lua 函数

c++ - Luabridge 绑定(bind)重载运算符

c++ - 从 C++ 访问 Lua 中的表

c++ - 如何为算术表达式创建 BST