Reading files
The read method takes formats like "a" for all, "l" for a line and "n" for a number.
In this page:
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
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
Login to try C/C++/Java/PHP code in the editor
Common Mistakes
- Expecting "l" to keep the newline
- Expecting "a" to return nil at the end
- 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: