private static int g_iofile(LuaState L, int f, CharPtr mode) { if (!lua_isnoneornil(L, 1)) { CharPtr filename = lua_tostring(L, 1); if (filename != null) { FilePtr pf = newfile(L); pf.file = fopen(filename, mode); if (pf.file == null) { fileerror(L, 1, filename); } } else { tofile(L); /* check that it's a valid file file */ lua_pushvalue(L, 1); } lua_rawseti(L, LUA_ENVIRONINDEX, f); } /* return current value */ lua_rawgeti(L, LUA_ENVIRONINDEX, f); return(1); }
/* ** function to close regular files */ private static int io_fclose(LuaState L) { FilePtr p = tofilep(L); int ok = (fclose(p.file) == 0) ? 1 : 0; p.file = null; return(pushresult(L, ok, null)); }
/* ** this function has a separated environment, which defines the ** correct __close for 'popen' files */ private static int io_popen(LuaState L) { CharPtr filename = luaL_checkstring(L, 1); CharPtr mode = luaL_optstring(L, 2, "r"); FilePtr pf = newfile(L); pf.file = lua_popen(L, filename, mode); return((pf.file == null) ? pushresult(L, 0, filename) : 1); }
/* ** When creating file files, always creates a `closed' file file ** before opening the actual file; so, if there is a memory error, the ** file is not left opened. */ private static FilePtr newfile(LuaState L) { FilePtr pf = (FilePtr)lua_newuserdata(L, typeof(FilePtr)); pf.file = null; /* file file is currently `closed' */ luaL_getmetatable(L, LUA_FILEHANDLE); lua_setmetatable(L, -2); return(pf); }
private static Stream tofile(LuaState L) { FilePtr f = tofilep(L); if (f.file == null) { luaL_error(L, "attempt to use a closed file"); } return(f.file); }
private static int io_tmpfile(LuaState L) { FilePtr pf = newfile(L); #if XBOX luaL_error(L, "io_tmpfile not supported on Xbox360"); #else pf.file = tmpfile(); #endif return((pf.file == null) ? pushresult(L, 0, null) : 1); }
private static int io_lines(LuaState L) { if (lua_isnoneornil(L, 1)) /* no arguments? */ /* will iterate over default input */ { lua_rawgeti(L, LUA_ENVIRONINDEX, IO_INPUT); return(f_lines(L)); } else { CharPtr filename = luaL_checkstring(L, 1); FilePtr pf = newfile(L); pf.file = fopen(filename, "r"); if (pf.file == null) { fileerror(L, 1, filename); } aux_lines(L, lua_gettop(L), 1); return(1); } }