Default files, os.remove and os.rename
io.write, io.read and friends use default files, and os handles deleting and renaming.
In this page:
Default files, os.remove and os.rename
io.output(path) redirects io.write to a file and io.input(path) redirects io.read, while io.stdout and io.stderr are always available. os.rename(old, new) and os.remove(path) manage files and return true on success, or nil plus a message on failure. Passing no argument to io.output returns the current default output file.
Note:
Restore the default output with io.output(io.stdout) before printing to the screen again.
Example: Default files, os.remove and os.rename
local a, b = "/tmp/lua_demo_a.txt", "/tmp/lua_demo_b.txt"
io.output(a)
io.write("written through default output\n")
io.close()
io.output(io.stdout)
print(os.rename(a, b))
io.input(b)
print(io.read("l"))
io.close(io.input())
io.input(io.stdin)
print(os.remove(b))
print(select("#", os.remove(b)))
-- Output:
-- true
-- written through default output
-- true
-- 3
Login to try C/C++/Java/PHP code in the editor
Common Mistakes
- Forgetting to restore io.output after redirecting
- Using os.remove on a file that does not exist and ignoring the failure
- Confusing io.write with file:write
Chapter Summary
- io.output redirects io.write
- io.input redirects io.read
- os.rename and os.remove return true or nil plus a message
- io.stdout and io.stderr are predefined
🔒
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: