luabind:无法调用基本的 lua 函数,如 print、tostring
我猜想一个非常基本的问题:
调用 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 这样的函数是在全局环境中定义的。那为什么找不到呢?
非常感谢。
A very basic question i guess:
The C++ code, calling lua looks like this:
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);
now test.lua has the following contents:
function main()
print "1"
end
Upon execution I receive the error:
test.lua:2: attempt to call global 'print' (a nil value)
What is the problem? It has something to do with environments? I thought functions like print are defined in the global environment. Why is it not found then?
Thank you very much.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
正如您所了解的,您必须调用 luaopen_base 来获取 print 和其他基本函数。然后你需要调用
luaopen_string
、luaopen_math
来获取基本模块和函数。无需手动全部写出来,可以使用<一次性加载所有Lua基本函数a href="http://www.lua.org/manual/5.1/manual.html#luaL_openlibs">luaL_openlibs
:As you figured it out, you have to call
luaopen_base
to getprint
and other base functions. Then you need to callluaopen_string
,luaopen_math
, to get the basic modules and functions in. Instead of writing it all out manually, can load all Lua base function at once withluaL_openlibs
: