🎓 A1Learner
🔍
0 of 52 lessons completed

Lua Reading Files Line by Line

A line iterator is a value that returns one line on each step of a loop. io.lines opens a file, returns its lines one by one, and closes the file when the lines run out.

Iterate with io.lines

io.lines takes the file path and returns its lines one by one. The loop ends when the lines run out.

local writer = io.open("colours.txt", "w")
writer:write("red\ngreen\nblue\n")
writer:close()
for line in io.lines("colours.txt") do
  print(line)
end

Iterate with a handle

A handle's :lines() method gives the same kind of loop. Close the handle after the loop finishes.

local writer = io.open("animals.txt", "w")
writer:write("cat\ndog\nbird\n")
writer:close()
local reader = io.open("animals.txt", "r")
for line in reader:lines() do
  print(line)
end
reader:close()

Stop reading early

A break leaves the loop at once, so later lines are never printed. The handle still needs its :close() call.

local writer = io.open("words.txt", "w")
writer:write("first\nsecond\nthird\nfourth\n")
writer:close()
local reader = io.open("words.txt", "r")
for line in reader:lines() do
  print(line)
  if line == "second" then
    break
  end
end
reader:close()

Example

local writer = io.open("fruit.txt", "w")
writer:write("apple\nbanana\nSTOP\ncherry\n")
writer:close()
local reader = io.open("fruit.txt", "r")
local count = 0
for line in reader:lines() do
  if line == "STOP" then
    break
  end
  print(line)
  count = count + 1
end
reader:close()
print(count)

Key points

  • io.lines: io.lines(path) returns an iterator over the lines of a file.
  • Handle lines: a handle's :lines() method returns an iterator over that handle's lines.
  • For loop: a for loop calls the iterator until it returns nil.
  • Early stop: breaking out of the loop stops reading before the file ends.
  • Close after a break: a handle stopped early must still be closed by the program.

In this example, the program writes four lines, including a STOP marker line. It reads with a handle iterator and breaks out of the loop when it reaches the marker. It closes the handle and prints the count of lines read before the marker.

Note

io.lines closes its own file when the loop ends, while a handle iterator leaves closing to the program.

Try it Yourself

Edit the code, then press Run.

Running is simulated

Exercise

What does io.lines do when its loop reaches the end of the file?