Standard Library: io, os and math
By the end of this lesson you'll use three workhorse standard libraries: io for reading and writing files and the console, os for time, dates, environment variables, and processes, and math for rounding, randomness, constants, and numeric helpers — the everyday toolkit behind real Lua scripts.
Learn Standard Library: io, os and math in our free Lua course — an interactive lesson with worked examples, a practice exercise and a quick reference.
Part of the free Lua course at LearnCodingFast — hands-on lessons with examples you run in your browser, plus practice exercises and a quick quiz.
The standard library is your program's workshop drawers . The io drawer holds the tools for moving things in and out — pens for writing files, a reader for taking them back in. The os drawer is the clock-and-calendar plus a phone line to the operating system: what time is it, what's in the environment, run this command. The math drawer is the calculator and dice cup. You don't build these tools yourself; you just know which drawer to open, and your scripts suddenly handle files, time, and numbers like a pro.
1. io: Files & the Console
The io library handles input and output. io.open(name, mode) returns a file handle (or nil plus a message on failure) — modes are "r" read, "w" write (which truncates !), and "a" append. With a handle you :write(...) , :read("a") for the whole file, or loop over :lines() for memory-friendly line-by-line reading, and you must :close() when done. io.write prints to stdout without formatting, and io.read reads from stdin. Read and run this.
2. os: Time, Dates, Environment & Processes
The os library is your link to the operating system. os.time() returns the current time as a number of seconds, which os.date(fmt) formats with strftime codes like %Y-%m-%d . os.clock() measures CPU time — ideal for benchmarking a block of code. os.getenv(name) reads an environment variable, os.execute(cmd) runs a shell command, and os.exit(code) ends the program with a status. Don't confuse os.time (wall-clock) with os.clock (CPU time).
Your turn. Write two scores to a file, then read them back line by line. Fill in the blanks marked ___ .
3. math: Rounding, Randomness & Constants
The math library covers numbers. Round with floor (down) and ceil (up). For randomness, seed once with math.randomseed(os.time()) so each run differs, then draw with math.random() (a float in [0,1) ), math.random(n) (an integer 1..n ), or math.random(a, b) (an integer a..b ). Reach for constants and helpers like math.pi , math.huge (infinity), math.sqrt , math.max / math.min , math.abs , and math.fmod . Read and run this.
Now you try combining os and math . Seed the generator, roll a die, and print today's date. Fill in the blanks:
No blanks this time — just a brief and an outline. You'll combine io.open (guarding its nil -plus-message return), a lines() loop, and optionally os.clock() to time it. Build it, run it, and check your output.
Practice quiz
Which function opens a file and returns a file handle?
- io.open
- io.file
- io.load
- io.read
Answer: io.open. io.open(name, mode) returns a file handle on success, or nil plus an error message on failure.
What does io.open return when it fails to open a file?
- It raises an error
- An empty handle
- nil and an error message
- false only
Answer: nil and an error message. io.open follows the nil-plus-message convention so you can check before using the handle.
Which mode string opens a file for writing, truncating existing contents?
- "a"
- "w"
- "x"
- "r"
Answer: "w". Mode 'w' opens for writing and discards any existing contents; 'a' appends, 'r' reads.
Which method reads a file one line at a time in a for loop?
- file:all()
- file:scan()
- file:next()
- file:lines()
Answer: file:lines(). file:lines() returns an iterator yielding each line, perfect for a for loop.
How do you read a whole line from standard input?
- io.read()
- io.scan()
- io.get()
- io.input()
Answer: io.read(). io.read() (defaulting to a line read) returns the next line typed on stdin.
Which os function returns the current time as a number of seconds?
- os.clock
- os.time
- os.tick
- os.now
Answer: os.time. os.time() returns the current time as a numeric timestamp (seconds since an epoch).
What does os.clock measure?
- The system uptime
- The file modification time
- Wall-clock date
- CPU time used by the program
Answer: CPU time used by the program. os.clock returns an approximation of CPU time used, useful for benchmarking code.
Which math function returns a pseudo-random number?
- math.dice
- math.rand
- math.random
- math.rnd
Answer: math.random. math.random() gives a float in [0,1); with arguments it returns an integer in a range.
Why call math.randomseed before using math.random?
- It is required or random errors
- To get a different sequence each run instead of a fixed one
- To make numbers larger
- To reset the io library
Answer: To get a different sequence each run instead of a fixed one. Seeding (often with os.time()) varies the sequence between runs; without it you may get the same numbers each time.
Which math value represents positive infinity?
- math.huge
- math.pi
- math.max
- math.inf
Answer: math.huge. math.huge is the representation of infinity; math.pi is the constant pi, not infinity.