luabind:无法调用print,tostring等基本的lua函数

时间:2012-02-24 13:07:03

标签: c++ lua environment luabind

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

调用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这样的函数是在全局环境中定义的。那为什么没找到?

非常感谢。

1 个答案:

答案 0 :(得分:6)

正如您所知,您必须致电luaopen_base以获取print和其他基本功能。然后,您需要调用luaopen_stringluaopen_math来获取基本模块和函数。而不是手动编写全部,可以使用luaL_openlibs一次加载所有Lua基函数:< / p>

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