luabind:无法调用类似print,tostring的基本lua函数。

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

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

非常感谢。

原文链接 https://stackoverflow.com/questions/9431297

点赞
stackoverflow用户221509
stackoverflow用户221509

正如您所猜测的那样,需要调用 luaopen_base 来获取 print 和其他基础函数。然后,需要调用 luaopen_stringluaopen_math 来获取基本模块和函数。与其手动编写所有内容,不如一次性加载所有 Lua 基本函数,可以使用 luaL_openlibs:

lua_State* m_L = luaL_newstate();
luaL_openlibs(m_L);
2012-02-25 17:34:03