Search code examples
debuggingfile-ioiolualua-5.2

Lua I/O works while debugging, but not in the program proper


I'm testing out writing to a file for the first time in a Lua (5.2.1) script, alternating between two versions:

Version 1

local ofile = io.open("save.txt", "w")
  ofile:write("Writing to file...")
  ofile:close()

Version 2

io.output("save.txt")
io.write("Writing to file...")
io.close()

Both of these work perfectly when debugging in ZeroBrane Studio, but when inserted in the script for my program, the file is not written to, and any code that comes after that point is apparently not executed.

I included the I/O library in my program, by the way.

lua_State *lua = luaL_newstate();

static const luaL_Reg lualibs[] = {
    { "base", luaopen_base }, 
    { "io", luaopen_io },
    { "string", luaopen_string },
    { "table",  luaopen_table },
    { NULL, NULL}
};

const luaL_Reg *lib = lualibs;
for(; lib->func != NULL; lib++) {
  lib->func(lua);
  lua_settop(lua, 0);
}

Solution

  • I determined that the issue related to how the Lua libraries were being loaded. Simply changing the individual loading to:

    luaL_openlibs(lua);
    

    fixed the entire issue. Yet I still don't understand why calling the I/O library by itself did not work.