0Pricing
Lua Academy · Lesson

Reading File Contents

Read lines, bytes, and full content with file:read() methods.

Read Entire File

Use f:read("a") (or "*a") to read the entire file into a string. This is simple and fine for small to medium files. For very large files, read in chunks or line by line to avoid memory issues.

local f = io.open("config.txt", "r")
if f then
  local content = f:read("a")
  f:close()
  print("Size:", #content, "bytes")
  print(content)
end

Read Line by Line

f:read("l") reads the next line, stripping the newline. Returns nil at EOF. Loop with while to process each line. f:lines() is the idiomatic shorthand that does the same thing.

local f = io.open("data.txt", "r")
if f then
  local line = f:read("l")
  while line ~= nil do
    print(line)
    line = f:read("l")
  end
  f:close()
end

-- Equivalent with for loop:
-- for line in io.lines("data.txt") do print(line) end

All lessons in this course

  1. Opening Files with io.open
  2. Reading File Contents
  3. Writing and Appending to Files
  4. Closing Files and Error Handling
← Back to Lua Academy