Lua Reading Files
Reading a file means getting its stored text back into a program. A file handle is the object Lua uses to read from an open file.
Read a file line by line
Open the file in mode "r". Call :read("*l") until it returns nil.
local writer = io.open("notes.txt", "w")
writer:write("one\n")
writer:write("two\n")
writer:write("three\n")
writer:close()
local reader = io.open("notes.txt", "r")
local line = reader:read("*l")
while line do
print(line)
line = reader:read("*l")
end
reader:close()Read a whole file at once
:read("*a") returns every remaining character as one string. Print that string to show the whole file.
local writer = io.open("notes.txt", "w")
writer:write("alpha\nbeta")
writer:close()
local reader = io.open("notes.txt", "r")
local content = reader:read("*a")
print(content)
reader:close()Reading past the end returns nil
The second read finds nothing left. Comparing it with nil gives true.
local writer = io.open("notes.txt", "w")
writer:write("only one")
writer:close()
local reader = io.open("notes.txt", "r")
local first = reader:read("*l")
local second = reader:read("*l")
print(first)
print(second == nil)
reader:close()Example
local writer = io.open("colours.txt", "w")
writer:write("red\ngreen\nblue\n")
writer:close()
local reader = io.open("colours.txt", "r")
local lines = {}
local line = reader:read("*l")
while line do
lines[#lines + 1] = line
line = reader:read("*l")
end
reader:close()
print(#lines)
print(lines[2])Key points
- Handle: io.open returns a handle for reading a file.
- Read mode: mode "r" opens an existing file for reading only.
- Line reading: :read("*l") returns one line at a time.
- End of file: :read returns nil when no lines remain.
- Whole file: :read("*a") returns the rest of the file as one string.
- Close: :close() releases a handle after reading is done.
In this example, the program writes three colour names to a file and closes it. It reopens the file for reading and stores each line in a table. It then prints how many lines were stored and the second line.
Note
A file opened for writing must be closed and reopened before it can be read.
Try it Yourself
Edit the code, then press Run.
Running is simulated
Exercise
What does :read("*l") return when the file has no more lines?