简体   繁体   English

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

[英]luabind: Can't call basic lua functions like print, tostring

A very basic question i guess: 我猜一个非常基本的问题:

The C++ code, calling lua looks like this: 调用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);

now test.lua has the following contents: 现在test.lua具有以下内容:

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. 我认为像print这样的功能是在全局环境中定义的。 Why is it not found then? 为什么找不到它呢?

Thank you very much. 非常感谢你。

As you figured it out, you have to call luaopen_base to get print and other base functions. 如您luaopen_base ,您必须调用luaopen_base以获得print和其他基本功能。 Then you need to call luaopen_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 with luaL_openlibs : 然后,您需要调用luaopen_stringluaopen_math来获取基本模块和函数。无需手动将其全部写入,可以使用luaL_openlibs一次加载所有Lua基本函数:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM