5

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.

1
  • The code creates a separate Lua state for each file that it runs. This will prevent different files from communicating. This may not be what you want. Commented May 6, 2013 at 16:57

1 Answer 1

4

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.

Sign up to request clarification or add additional context in comments.

3 Comments

Thanks, it works properly now, I use luaL_openlibs instead. I'll keep in mind your advise !
It helps. Could you please elaborate on why luaopen_* does not work? It is the first thing you see in their documentation
@VladLazarenko The luaopen_* functions simply create a table (mostly containing functions) on top of the stack. What is missing is associating that table with a name so that it can be accessed from within Lua and registering it with the module loading mechanism. Those two steps however are the same for all libraries. Think of the luaopen_* function as what the library writer provides for setting up that particular library. Its goal is not to do the complete library loading but rather provide the information that luaL_requiref needs to perform the loading instead.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.