I/O & Operating System Subsystems (`io`, `os`)
Interact with the host operating system, execute terminal commands, inspect system clocks, and perform high-speed buffered file input/output.
1. File Input/Output (`io`)
file_io.lua
-- Writing text to a file:
file = io.open("savegame.json", "w")
if (file) {
file:write('{"level": 5, "score": 1200}\n')
file:close()
}
-- Reading all content using RAII scope cleanup:
function loadConfig(path) {
local f <close> = io.open(path, "r")
if (not f) { return nil }
return f:read("*a") -- Read entire file
}
-- Iterating through lines of a file:
for line in io.lines("config.ini") {
print("Config Line: " .. line)
}
2. Operating System (`os`)
| Function | Signature | Description |
|---|---|---|
os.time([t]) |
([table]) → int |
Returns epoch timestamp in seconds. Pass date table to convert to timestamp. |
os.date([fmt, [time]]) |
([str, [int]]) → str|tbl |
Formats timestamp into a string (e.g. "%Y-%m-%d %H:%M:%S") or table ("*t"). |
os.clock() |
() → num |
Returns CPU execution seconds. Used for microsecond-accurate benchmarking. |
os.getenv(var) |
(str) → str|nil |
Retrieves the string value of an environment variable (e.g. "PATH", "USER"). |
os.execute([cmd]) |
([str]) → (bool, str, int) |
Executes an OS shell command and returns status. |
os.remove(path) |
(str) → (bool, [str]) |
Deletes the file at path. |
os.rename(old, new) |
(str, str) → (bool, [str]) |
Renames or moves a file. |
os.exit([code]) |
([int]) → none |
Terminates the host process immediately with exit code code (0 for success). |
Benchmark Timing Example
benchmark.lua
import os
startTime = os.clock()
-- Execute 1,000,000 iterations:
sum = 0
for i = 1, 1000000 {
sum = sum + i
}
elapsed = os.clock() - startTime
print(string.format("Calculated sum in %.4f seconds!", elapsed))