-1

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);
}
tshepang
  • 12,111
  • 21
  • 91
  • 136
M89
  • 71
  • 1
  • 6
  • 1
    This shouldn't be the problem, but just curious, try changing the file to `c:/test.txt` instead of just `test.txt` –  Nov 25 '12 at 22:02
  • I tried that out. Same thing--it worked while debugging, but failed in the actual program. – M89 Nov 25 '12 at 22:05
  • 1
    Is your program checking for errors when it executes this code? – Nicol Bolas Nov 25 '12 at 22:41

1 Answers1

0

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.

M89
  • 71
  • 1
  • 6