Skip to content
I/O and File Handling
step 1/4

Reading — step 1 of 4

Learn

~2 min readModules, Iterators, I/O

io is Lua's I/O library. Two main interfaces: simple (io.read, io.write) and object-oriented (file handles).

Simple I/O — operates on stdin/stdout:

io.write("prompt: ")        -- no newline
local line = io.read()        -- one line, no trailing \n
io.write("got: ", line, "\n")

io.read formats:

  • "*l" or "l" — one line (default)
  • "*n" or "n" — a number
  • "*a" or "a" — entire remaining input as one string
  • "*L" or "L" — line WITH newline
  • n (number) — n bytes

File handles:

local f, err = io.open("data.txt", "r")
if not f then
    print("error: " .. err)
    return
end

local content = f:read("*a")
f:close()

Modes (same letters as C):

  • "r" — read
  • "w" — write (truncate)
  • "a" — append
  • "r+" / "w+" / "a+" — read AND write
  • Add "b" for binary on Windows: "rb", "wb"

Iterating lines:

for line in io.lines("data.txt") do
    print(line)
end

File is opened, all lines yielded, then closed when iteration ends. Best for line-by-line processing.

Writing:

local f = io.open("out.txt", "w")
f:write("hello\n")
f:write(string.format("%d items\n", 42))
f:close()

f:write accepts strings or numbers, no automatic newline (unlike print).

io.stdout / io.stderr — pre-opened handles:

io.stderr:write("warning: " .. msg .. "\n")

Default destinations for io.write (stdout) and the read end (stdin) are also accessible:

io.input("data.txt")     -- redirect default input
local s = io.read("*a")
io.input(io.stdin)        -- restore

Always close: handles aren't GC'd reliably. Use f:close() or wrap in pcall + finalizer.

os library for filesystem ops:

  • os.remove(path) — delete
  • os.rename(old, new) — rename
  • os.tmpname() — temp file path
  • os.date(fmt) — format current time
  • os.time() — Unix timestamp
  • os.getenv("HOME") — environment variable
  • os.execute(cmd) — shell command (sandboxed environments often disable)

For heavy file I/O, libraries like lfs (LuaFileSystem) add directory listing, attributes, etc.

Discussion

Ask a question, share an insight, or help someone who’s stuck.

Sign in to post a comment or reply.

Loading…