使用C++的Lua脚本:尝试索引全局'io'(零值)

Boi*_*ime 5 c++ io lua

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

-- toto.lua:1: attempt to index global 'io' (a nil value)
Run Code Online (Sandbox Code Playgroud)

这是我的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;
  }
Run Code Online (Sandbox Code Playgroud)

非常感谢.

Com*_*sMS 4

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

luaL_requiref(L, "io", luaopen_io, 1);
Run Code Online (Sandbox Code Playgroud)

这里的特殊问题是luaopen_io不将模块表存储在 中_G,因此抱怨它io是一个nil值。如果您想了解详细信息,请查看 lauxlib.c 中 luaL_requiref 的源代码。