5

我打算使用lua fo AI编写一个程序,所以我试图让它一起工作。但是当我尝试从我的 cpp 文件加载一个 lua 脚本时,我收到了这个错误消息:

-- toto.lua:1: attempt to index global 'io' (a nil value)

这是我的 lua 脚本:

io.write("Running ", _VERSION, "\n")

这是我的 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;
  }

非常感谢。

4

1 回答 1

4

你不应该直接调用 luaopen_* 函数。使用luaL_openlibsluaL_requiref代替:

luaL_requiref(L, "io", luaopen_io, 1);

这里的特殊问题是luaopen_io不将模块表存储在 中_G,因此抱怨io是一个nil值。如果你想知道血淋淋的细节,请查看 luxlib.c 中 luaL_requiref 的源代码。

于 2013-05-06T13:33:52.867 回答