Writing and Appending to Files
Write strings to files and append data without overwriting.
f:write() Basics
f:write(...) writes one or more strings (or numbers) to the file. It does not add newlines automatically. Returns the file handle on success (enabling chaining), or nil, errMessage, errCode on failure.
local f = io.open("output.txt", "w")
if f then
f:write("Hello, ")
f:write("World")
f:write("!\n")
f:write("Line 2\n")
f:close()
endWriting Multiple Values
f:write() accepts multiple arguments and writes them all sequentially. Values must be strings or numbers — passing other types raises an error. Use tostring() to convert booleans, tables, etc.
local f = io.open("log.txt", "w")
f:write("Name: ", "Alice", "\n")
f:write("Age: ", 30, "\n")
f:write("Score: ", string.format("%.1f", 95.5), "\n")
f:close()All lessons in this course
- Opening Files with io.open
- Reading File Contents
- Writing and Appending to Files
- Closing Files and Error Handling