Lua Writing Files
Writing a file means storing text in a file for later use. Mode "w" creates or replaces a file, and mode "a" adds to an existing file.
Mode w replaces the old contents
Write an old word, close the file, then open it again with "w". The new word replaces the old one.
local writer = io.open("word.txt", "w")
writer:write("old")
writer:close()
writer = io.open("word.txt", "w")
writer:write("new")
writer:close()
local reader = io.open("word.txt", "r")
print(reader:read("*a"))
reader:close()Mode a keeps the old contents
Write one line, close the file, then reopen it with "a". The new line lands after the old one.
local writer = io.open("word.txt", "w")
writer:write("one\n")
writer:close()
writer = io.open("word.txt", "a")
writer:write("two\n")
writer:close()
local reader = io.open("word.txt", "r")
local line = reader:read("*l")
while line do
print(line)
line = reader:read("*l")
end
reader:close()Write takes several values
:write stores its values one after another. A space between words must be written as its own value.
local writer = io.open("score.txt", "w")
writer:write("score", " ", 42, "\n")
writer:close()
local reader = io.open("score.txt", "r")
print(reader:read("*l"))
reader:close()Example
local writer = io.open("day.txt", "w")
writer:write("morning\n")
writer:write("noon\n")
writer:close()
writer = io.open("day.txt", "a")
writer:write("night\n")
writer:close()
local reader = io.open("day.txt", "r")
local line = reader:read("*l")
while line do
print(line)
line = reader:read("*l")
end
reader:close()Key points
- Write mode: mode "w" opens a file for writing and erases its old contents.
- Append mode: mode "a" opens a file for writing at its end.
- Write call: :write() stores each value it is given, in order.
- Close first: a file must be closed before it is reopened for reading.
- Reopen to check: reopening in mode "r" lets a program read back what it wrote.
In this example, the program writes two lines with mode "w" and closes the file. It then appends a third line with mode "a" and closes the file again. Finally it reopens the file and prints all three lines in order.
Note
Opening an existing file with "w" loses the old contents, so use "a" when the old contents must stay.
Try it Yourself
Edit the code, then press Run.
Running is simulated
Exercise
What happens to the old contents when a file is opened with "w"?