我猜是一个非常基本的问题:
调用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这样的函数是在全局环境中定义的。那为什么没找到?
非常感谢。
答案 0 :(得分:6)
正如您所知,您必须致电luaopen_base
以获取print
和其他基本功能。然后,您需要调用luaopen_string
,luaopen_math
来获取基本模块和函数。而不是手动编写全部,可以使用luaL_openlibs
一次加载所有Lua基函数:< / p>
lua_State* m_L = luaL_newstate();
luaL_openlibs(m_L);