I/O operations
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.
Important 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 descriptors with io.output and io.input.
Modes
The following file modes are available:
Figure 19.4 – File modes in Lua
Opening a file
The io.open function 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).
Reading a file
To read a file using an explicit file descriptor, use the io.read function:
file = io.open(filename) val = file:io.read("%d")
There is a function named io.lines that will take a filename as an argument and return an iterator to traverse...