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)
endRead 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