0Pricing
Lua Academy · Lesson

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()
end

Writing 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

  1. Opening Files with io.open
  2. Reading File Contents
  3. Writing and Appending to Files
  4. Closing Files and Error Handling
← Back to Lua Academy