[英]Lua script with C++ : attempt to index global 'io' (a nil value)
I'm going to write a program using lua fo AI, so I'm trying to make it works together. 我打算用lua fo AI写一个程序,所以我试着让它一起工作。 But when I try to load a lua script from my cpp file I've got this error message :
但是当我尝试从我的cpp文件加载lua脚本时,我收到此错误消息:
-- toto.lua:1: attempt to index global 'io' (a nil value)
Here is my lua script : 这是我的lua脚本:
io.write("Running ", _VERSION, "\\n")
And here is my cpp file : 这是我的cpp文件:
void report_errors(lua_State *L, int status)
{
if ( status!=0 ) {
std::cerr << "-- " << lua_tostring(L, -1) << std::endl;
lua_pop(L, 1); // remove error message
}
}
int main(int argc, char** argv)
{
for ( int n=1; n<argc; ++n ) {
const char* file = argv[n];
lua_State *L = luaL_newstate();
luaopen_io(L); // provides io.*
luaopen_base(L);
luaopen_table(L);
luaopen_string(L);
luaopen_math(L);
std::cerr << "-- Loading file: " << file << std::endl;
int s = luaL_loadfile(L, file);
if ( s==0 ) {
s = lua_pcall(L, 0, LUA_MULTRET, 0);
}
report_errors(L, s);
lua_close(L);
std::cerr << std::endl;
}
return 0;
}
Thanks a lot. 非常感谢。
You should not call the luaopen_* functions directly. 你不应该直接调用luaopen_ *函数。 Use either luaL_openlibs or luaL_requiref instead:
使用luaL_openlibs或luaL_requiref代替:
luaL_requiref(L, "io", luaopen_io, 1);
The particular problem here is that luaopen_io
does not store the module table in _G
, hence the complaint that io
is a nil
value. 这里的特殊问题是
luaopen_io
没有在_G
存储模块表,因此抱怨io
是nil
值。 Take a look at the source code for luaL_requiref in lauxlib.c if you want to know the gory details. 如果你想了解血腥细节,请查看lauxlib.c中luaL_requiref的源代码。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.