File manipulation in Lua is done either on implicit or explicit file descriptors. We will focus on using explicit file descriptors to perform most of the operations.
Note
If we work with implicit file descriptors, by default, Lua will use stdin
and stdout
, respectively. Alternatively, we can set the output and input descriptor with io.output
and io.input
.
The following file modes are available:
r | Read mode. |
w | Write mode. |
a | Append mode. |
r+ | Update mode. This mode preserves the existing data. |
w+ | Update mode. This mode deletes any existing data. |
a+ | Append update mode. This mode preserves the existing data and only allows appending at the end of file. |
The function io.open
returns a file descriptor if successful:
file = io.open (filename [, mode])
When it fails, it will return nil and the corresponding error message (like most Lua functions).