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

chr*_*tte 5 c++ environment lua 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);
Run Code Online (Sandbox Code Playgroud)

现在test.lua具有以下内容:

function main()
print "1"
end
Run Code Online (Sandbox Code Playgroud)

执行后,我收到错误:

test.lua:2: attempt to call global 'print' (a nil value)
Run Code Online (Sandbox Code Playgroud)

问题是什么?它与环境有关吗?我认为像print这样的函数是在全局环境中定义的.那为什么没找到?

非常感谢你.

Mic*_*man 6

当你想出来时,你必须调用luaopen_baseget print和其他基本函数.然后你需要调用luaopen_string,luaopen_math以获得基本模块和函数.而不是手动编写全部,可以一次加载所有Lua基函数luaL_openlibs:

lua_State* m_L = luaL_newstate();
luaL_openlibs(m_L);
Run Code Online (Sandbox Code Playgroud)