Lua:在原生 Lua 中编译没有问题,但在 LuaJIT 和 sol2 的 C++ 中出现错误

我有以下 Lua 代码,在 在线解释器 上运行正常:

__sprite_properties = {
    events = {}
}

function bind_event(event_name, fun)
    table.insert(__sprite_properties.events, { event_name, fun })
    print(__sprite_properties.events[1][1])
end

foo = function()
    return 0
end
bind_event("foo_event", foo)

>> foo_event

但是当我使用 sol2 库在 C++ 中加载和运行脚本时,我在 table.insert 语句处得到以下错误:

script.lua:6: attempt to index global 'table' (a nil value)

stack traceback: script.lua:6: in function 'bind_event' -- script.lua:13: in main chunk

我正在使用 LuaJIT 作为 Lua 分发。 用于在 Lua 中加载脚本的代码如下片段所示:

sol::state lua;
lua.open_libraries(sol::lib::base);
try {
    lua.safe_script_file("script.lua");
}
catch (const sol::error& e) {
    std::cout << e.what() << std::endl;
}

为什么当在 C++ 中加载时,这段代码无法正确执行呢?

点赞
用户107090
用户107090

你在 C++ 代码中加载了 Lua 的标准库吗?似乎你只加载了基础库,而没有加载表库:

lua.open_libraries(sol::lib::base);
2018-06-23 11:17:49