Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Lua script with C++ : attempt to index global 'io' (a nil value)

Tags:

c++

io

lua

I'm going to write a program using lua fo AI, so I'm trying to make it works together. But when I try to load a lua script from my cpp file I've got this error message :

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

Here is my lua script :

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

And here is my cpp file :

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.

like image 571
BoilingLime Avatar asked Oct 04 '22 05:10

BoilingLime


1 Answers

You should not call the luaopen_* functions directly. Use either luaL_openlibs or luaL_requiref instead:

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. Take a look at the source code for luaL_requiref in lauxlib.c if you want to know the gory details.

like image 106
ComicSansMS Avatar answered Oct 13 '22 09:10

ComicSansMS