How to read all the lines in a file?
The simplest method is to use io.lines
:
for line in io.lines 'myfile.txt' do
...
end
This form opens the file for you and ensures that it is closed afterwards. Without an argument, io.lines()
gives you an iterator over all lines from standard input. Note that it is an iterator, this does not bring the whole file into memory initially.
It is better to open a file explicitly using io.open
, since you can do proper error checking:
local f,err = io.open(file)
if not f then return print(err) end for line in f:lines() do
...
end f:close()
This is equivalent to:
local line = f:read() -- by default, `read` reads a line while line do
...
line = f:read()
end
To read a whole file as a string, use the *a
format with read
:
s = f:read '*a'