Lua by Example: File Handling
Lua provides a simple I/O library. This sample demonstrates writing to and reading from files.
Code
-- Writing to a file
local file = io.open("test.txt", "w")
if file then
file:write("Hello, File!\n")
file:write("Line 2")
file:close()
else
print("Could not open file for writing")
end
-- Reading from a file
local file = io.open("test.txt", "r")
if file then
-- Read the whole file
local content = file:read("*a")
print("File Content:")
print(content)
file:close()
end
-- Reading line by line
for line in io.lines("test.txt") do
print("Line: " .. line)
endExplanation
Lua's I/O library offers two models: simple (using default input/output files) and complete (using file handles). The complete model, shown here, uses io.open() to create a file handle. The mode string "w" is for writing (overwriting), "r" for reading, and "a" for appending.
Once you have a file handle, you can call methods on it using the colon syntax, like file:write() and file:read(). The read method accepts format strings; "*a" reads the entire file, "*l" reads a line (default), and "*n" reads a number. Always remember to call file:close() to release system resources.
For simple line-by-line iteration, io.lines("filename") is a convenient shortcut. It opens the file and returns an iterator that yields each line of the file, automatically closing the file when the loop finishes. This is memory-efficient for processing large files.
Code Breakdown
io.open(..., "w") opens the file. It returns a handle or nil, error_message on failure.file:read("*a") reads "all" content from the current position to the end.
