← Back to Lua Course | Chapter 8: File I/O | Lesson 2 of 7

Writing to files

The write method saves strings and numbers to a file without adding newlines.

In this page:

  1. Writing to files

Writing to files

file:write accepts any number of strings and numbers and writes them exactly as given, so include \n yourself. It returns the file handle so calls can be chained. Numbers are converted using the usual format, and other types must be converted with tostring first.

Note: Use string.format together with write for tidy, structured lines.

Example: Writing to files

lua
local path = "/tmp/lua_demo_write.txt"
local f = assert(io.open(path, "w"))
f:write("line one\n")
f:write("line ", 2, "\n"):write(string.format("pi is %.2f\n", math.pi))
f:close()

local r = assert(io.open(path, "r"))
print(r:read("a"))
r:close()

-- Output:
-- line one
-- line 2
-- pi is 3.14
Common Mistakes
  1. Expecting write to add a newline
  2. Passing a table or nil to write
  3. Using a dot instead of a colon in f.write("x")
Chapter Summary
  • write does not add newlines
  • It accepts strings and numbers
  • It returns the file for chaining
  • Use the colon syntax f:write
🔒

Chapter Quiz — Complete all 7 topics to unlock

0/7 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.