← Back to Lua Course | Chapter 8: File I/O | Lesson 4 of 7

Iterating lines

io.lines and file:lines let you loop over a file one line at a time.

In this page:

  1. Iterating lines

Iterating lines

file:lines returns an iterator over the lines of an open file, and io.lines(path) opens the file, iterates and closes it automatically at the end. Each line comes without the newline character. This is memory friendly for large files because only one line is held at a time.

Note: io.lines raises an error if the file cannot be opened, so wrap it in pcall when the file may not exist.

Example: Iterating lines

lua
local path = "/tmp/lua_demo_lines.txt"
local w = assert(io.open(path, "w"))
w:write("alpha\nbeta\n\ngamma\n")
w:close()

local n = 0
for line in io.lines(path) do
  n = n + 1
  print(n, "[" .. line .. "]")
end
print(pcall(io.lines, "/tmp/definitely_missing_file.txt"))

-- Output:
-- 1	[alpha]
-- 2	[beta]
-- 3	[]
-- 4	[gamma]
-- false	cannot open file '/tmp/definitely_missing_file.txt' (No such file or directory)
Common Mistakes
  1. Forgetting that lines strips the newline
  2. Using io.lines on a missing file without pcall
  3. Reading the whole file into memory when a line loop is enough
Chapter Summary
  • io.lines(path) auto-closes the file
  • file:lines iterates an open file
  • Lines exclude the newline
  • Good for big files
🔒

Chapter Quiz — Complete all 7 topics to unlock

0/7 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.