io and os Libraries
29.1 Files
-- Write
local f = assert(io.open("notes.txt", "w")) -- modes: r, w, a, r+, w+, a+, plus b for binary
f:write("Line 1\n", "Line 2\n", 42, "\n")
f:close()
-- Read whole file
local f2 = assert(io.open("notes.txt", "r"))
local content = f2:read("a") -- "a" = all ("*a" in 5.1/5.2)
f2:close()
-- Read line by line
for line in io.lines("notes.txt") do print(line) end
local fh = assert(io.open("notes.txt"))
for line in fh:lines() do print(line) end
fh:close()
-- Read formats: "l" (line without newline), "L" (line with newline), "n" (number), "a" (all), n (n bytes)
local h = assert(io.open("numbers.txt"))
local a, b = h:read("n", "n")
h:close()
-- Append, seek, buffering
local log = assert(io.open("app.log", "a"))
log:setvbuf("line") -- "no", "full", "line"
log:write(os.date("%Y-%m-%d %H:%M:%S"), " started\n")
log:close()
local bin = assert(io.open("data.bin", "rb"))
local size = bin:seek("end") -- file size
bin:seek("set", 0)
local header = bin:read(4)
bin:close()
-- Default input/output
io.write("Enter your name: ")
local name = io.read("l")
io.output("out.txt"); io.write("redirected\n"); io.output():close(); io
…29.2 The os Library
The standard library has no directory listing or mkdir. Use LuaFileSystem (lfs.dir, lfs.mkdir, lfs.attributes) or luv / luaposix.
print(os.time()) -- epoch seconds
print(os.time{year = 2025, month = 10, day = 24, hour = 12})
print(os.date("%Y-%m-%d %H:%M:%S")) -- formatted local time
print(os.date("!%Y-%m-%dT%H:%M:%SZ")) -- UTC (! prefix)
local d = os.date("*t") -- table: year, month, day, hour, min, sec, wday, yday, isdst
print(d.year, d.month, d.day)
print(os.difftime(os.time(), os.time{year = 2025, month = 1, day = 1}) / 86400, "days")
print(os.clock()) -- CPU time used (for benchmarking)
print(os.getenv("HOME") or os.getenv("USERPROFILE"))
print(os.execute("echo hi")) -- 5.2+: true/nil, "exit", code
os.remove("temp.txt"); os.rename("a.txt", "b.txt")
print(os.tmpname())
-- os.exit(0) / os.exit(false) / os.exit(true, true) (close the state)
os.setlocale("C")