luabind:不能调用基本的lua函数,如print,tostring。

luabind: Can't call basic lua functions like print, tostring

本文关键字:函数 print tostring lua 不能 调用 luabind      更新时间:2023-10-16

我想这是一个非常基本的问题:

调用lua的C++代码如下所示:

lua_State* m_L;
m_L = lua_open();
luabind::open(m_L);
luaL_dofile(m_L, "test.lua");
try {
    luabind::call_function<void>(m_L, "main");
} catch (luabind::error& e) {
    std::string error = lua_tostring(e.state(), -1);
    std::cout << error << std::endl;
}
lua_close(m_L);

现在test.lua有以下内容:

function main()
print "1"
end

执行后,我收到错误:

test.lua:2: attempt to call global 'print' (a nil value)

问题出在哪里?这和环境有关吗?我认为像print这样的函数是在全局环境中定义的。为什么没有找到?

非常感谢。

正如您所了解的,您必须调用luaopen_base才能获得print和其他基本函数。然后你需要调用luaopen_stringluaopen_math来获取基本的模块和函数。不用手动写出来,可以用luaL_openlibs:一次加载所有的Lua基本函数

lua_State* m_L = luaL_newstate();
luaL_openlibs(m_L);