This first edition was written for Lua 5.0. While still largely relevant for later versions, there are some differences.
The fourth edition targets Lua 5.3 and is available at Amazon and other bookstores.
By buying the book, you also help to support the Lua project.


21.3 – Other Operations on Files

The tmpfile function returns a handle for a temporary file, open in read/write mode. That file is automatically removed (deleted) when your program ends. The flush function executes all pending writes to a file. Like the write function, you can call it as a function, io.flush(), to flush the current output file; or as a method, f:flush(), to flush file f.

The seek function can be used both to get and to set the current position of a file. Its general form is filehandle:seek(whence, offset). The whence parameter is a string that specifies how the offset will be interpreted. Its valid values are "set", when offsets are interpreted from the beginning of the file; "cur", when offsets are interpreted from the current position of the file; and "end", when offsets are interpreted from the end of the file. Independently of the value of whence, the call returns the final current position of the file, measured in bytes from the beginning of the file.

The default value for whence is "cur" and for offset is zero. Therefore, the call file:seek() returns the current file position, without changing it; the call file:seek("set") resets the position to the beginning of the file (and returns zero); and the call file:seek("end") sets the position to the end of the file, and returns its size. The following function gets the file size without changing its current position:

    function fsize (file)
      local current = file:seek()      -- get current position
      local size = file:seek("end")    -- get file size
      file:seek("set", current)        -- restore position
      return size
    end

All the previous functions return nil plus an error message in case of errors.