Skip to content
AgileLogics
4 min read

Input and Command-Line Arguments

Prerequisites: Functions

Reading from the keyboard

-- illustrative
io.write("What is your name? ")
local name = io.read("l")
io.write("How old are you? ")
local age = tonumber(io.read("l"))

if age then
  print("Hi " .. name .. ", next year you'll be " .. age + 1 .. ".")
else
  print("Hi " .. name .. ", that wasn't a number.")
end
What is your name? Ada
How old are you? 36
Hi Ada, next year you'll be 37.
  • io.read("l") reads one line (without the newline); io.read("n") reads a number.
  • It returns nil at the end of input — check for it in loops.

Reading all lines

-- illustrative
local total = 0
for line in io.lines() do
  total = total + (tonumber(line) or 0)
end
print("Sum: " .. total)

Run it with piped input: printf "1\n2\nx\n3\n" | lua sum.lua prints Sum: 6.

Command-line arguments

Arguments after the script name are in the global table arg:

-- illustrative
-- greet.lua
local name = arg[1] or "world"
local times = tonumber(arg[2]) or 1
for _ = 1, times do
  print("Hello, " .. name .. "!")
end
print("(" .. #arg .. " arguments, script: " .. arg[0] .. ")")
$ lua greet.lua Ada 2
Hello, Ada!
Hello, Ada!
(2 arguments, script: greet.lua)

arg[0] is the script name. The main chunk also receives the arguments as ..., so local name, times = ... works too.

Note that io and arg exist in the standalone lua interpreter — in a game engine or editor, the host decides what's available.