0Pricing
Lua Academy · Lesson

Reading File Contents

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

Reading File Contents is a free Lua Academy lesson on CoddyKit — lesson 2 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the Lua Academy learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.

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

Read Fixed Number of Bytes

Pass a number to f:read(n) to read exactly n bytes. Returns a string of up to n bytes (fewer if EOF is reached), or nil at EOF. Use for binary protocols or structured file formats.

local f = io.open("binary.dat", "rb")
if f then
  -- Read 4-byte header
  local header = f:read(4)
  if header then
    print("Header bytes:", #header)
    for i = 1, #header do
      io.write(string.format("%02X ", header:byte(i)))
    end
    print()
  end
  f:close()
end

Read a Number

f:read("n") reads the next number from the file, skipping whitespace. Returns a Lua number, or nil if the next token is not a number. Useful for reading structured numeric data files.

-- File contains: "10 20 30.5 40"
local f = io.open("nums.txt", "r")
if f then
  local total = 0
  local n = f:read("n")
  while n do
    total = total + n
    n = f:read("n")
  end
  f:close()
  print("Sum:", total)
end

Seeking in Files

f:seek(whence, offset) moves the file position. whence is "set" (from start), "cur" (from current), or "end" (from end). Returns the new absolute position. Use to re-read or jump around in files.

local f = io.open("test.txt", "r")
if f then
  -- Jump to end, get file size
  local size = f:seek("end")
  print("File size:", size, "bytes")
  
  -- Seek back to start
  f:seek("set", 0)
  local first_line = f:read("l")
  print("First line:", first_line)
  f:close()
end

Reading CSV Files

Parse CSV data line by line: read each line, then split by comma using string.gmatch. Handle quoted fields and commas within quotes for production use, but for simple data the basic split works.

local function parseCSV(path)
  local rows = {}
  for line in io.lines(path) do
    local row = {}
    for field in string.gmatch(line, "([^,]+)") do
      row[#row+1] = field
    end
    rows[#rows+1] = row
  end
  return rows
end

-- Example: "Alice,30,Engineer"
-- => {{"Alice","30","Engineer"}}

Reading Config Files

A simple key=value config format: read line by line, skip comments and blank lines, parse key=value pairs with string.match.

local function loadConfig(path)
  local cfg = {}
  for line in io.lines(path) do
    -- Skip comments and blank lines
    if not line:match("^%s*#") and line:match("%S") then
      local k, v = line:match("^%s*(%w+)%s*=%s*(.-)%s*$")
      if k then cfg[k] = v end
    end
  end
  return cfg
end

local config = loadConfig("app.conf")
print(config.host, config.port)

Chunked Reading

For large files, read in fixed-size chunks to avoid loading everything into memory. Process each chunk as it arrives. This is essential for files larger than available RAM.

local function processLarge(path, chunkSize)
  chunkSize = chunkSize or 4096
  local f, err = io.open(path, "rb")
  if not f then return nil, err end
  local totalBytes = 0
  local chunk = f:read(chunkSize)
  while chunk do
    totalBytes = totalBytes + #chunk
    -- process chunk here
    chunk = f:read(chunkSize)
  end
  f:close()
  return totalBytes
end

Reading Multiple Values Per Line

When each line contains multiple space-separated or tab-separated values, use string.match or string.gmatch to extract them. This pattern handles simple structured text files.

-- File: "Alice 95 A\nBob 87 B"
local results = {}
for line in io.lines("grades.txt") do
  local name, score, grade = line:match("(%S+)%s+(%d+)%s+(%S+)")
  if name then
    results[#results+1] = {
      name=name,
      score=tonumber(score),
      grade=grade
    }
  end
end

for _, r in ipairs(results) do
  print(r.name, r.score, r.grade)
end

io.lines Shortcut

io.lines(filename) opens the file, returns a line iterator, and closes the file when done. It's the most concise way to read a file line by line without managing the handle explicitly.

-- Count non-empty lines
local count = 0
for line in io.lines("data.txt") do
  if line:match("%S") then
    count = count + 1
  end
end
print("Non-empty lines:", count)

-- Collect all lines into a table
local lines = {}
for line in io.lines("data.txt") do
  lines[#lines+1] = line
end
print("Total lines:", #lines)

Quick Check

What does f:read("a") return when the file pointer is already at EOF?

Recap: Reading Files

Summary:

  • f:read("a") — entire file as string
  • f:read("l") — one line, no newline
  • f:read(n) — exactly n bytes
  • f:read("n") — next number
  • io.lines(path) — line iterator, auto-closes
  • f:seek() — jump to position

Frequently asked questions

Is the “Reading File Contents” lesson free?

Yes — the full text of “Reading File Contents” is free to read here on the web, and the Lua Academy course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the Lua Academy course, upgrade to CoddyKit PRO.

What will I learn in “Reading File Contents”?

Read lines, bytes, and full content with file:read() methods. You practise Lua Academy with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.

Do I need any experience to start Lua Academy?

No prior experience is required. Lua Academy on CoddyKit is structured for beginners through advanced learners; this is — lesson 2 of 4, so you can start here or from the beginning and move at your own pace.

How long does the “Reading File Contents” lesson take?

Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.

Can I write and run code in this Lua Academy lesson?

Yes. Every Lua Academy lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.

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