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

Reading files

The read method takes formats like "a" for all, "l" for a line and "n" for a number.

In this page:

  1. Reading files

Reading files

file:read accepts formats such as "a" for the whole rest of the file, "l" for the next line without its newline, "L" to keep the newline, "n" for a number and a plain integer for that many bytes. At the end of the file read returns nil, except that "a" returns an empty string. You can pass several formats and get several results.

Note: In Lua 5.3 the formats are written without the star, though the older "*a" style is still accepted.

Example: Reading files

lua
local path = "/tmp/lua_demo_read.txt"
local w = assert(io.open(path, "w"))
w:write("first line\n42 3.5\nlast")
w:close()

local f = assert(io.open(path, "r"))
print(f:read("l"))
print(f:read("n", "n"))
print(f:read(1) == "\n")
print(f:read("a"))
print(f:read("a") == "", f:read("l"))
f:close()

-- Output:
-- first line
-- 42	3.5
-- true
-- last
-- true	nil
Common Mistakes
  1. Expecting "l" to keep the newline
  2. Expecting "a" to return nil at the end
  3. Reading a number with "n" from text that is not numeric
Chapter Summary
  • "a" reads everything
  • "l" reads a line without newline
  • "n" reads a number
  • A count reads that many bytes
🔒

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.