Lua Multiple Returns
A Lua function can return several values at once. There is no need to pack them into a list or an object: the caller just receives them in multiple variables.
local function minMax(list)
local lo, hi = list[1], list[1]
for i = 2, #list do
if list[i] < lo then lo = list[i] end
if list[i] > hi then hi = list[i] end
end
return lo, hi
end
local smallest, largest = minMax({ 7, 2, 9, 4 })
print(smallest, largest)2 9
The standard library uses this everywhere: string.find returns a start and an end position, pcall returns a status and a result, math.modf returns two parts.
Receiving values
Extra values are dropped, missing ones become nil, and _ is a conventional name for values you don't care about:
local function threeValues() return "a", "b", "c" end
local x = threeValues()
print(x)
local p, q, r, s = threeValues()
print(p, q, r, s)
local _, second = threeValues()
print(second)a
a b c nil
b
The adjustment rule
How many values a call produces depends on where the call appears:
- As the last (or only) item in a list of expressions (arguments, assignment right-hand side, table constructor,
return), the call expands to all its values. - Anywhere else, it is cut to exactly one value.
- Wrapping a call in parentheses
(f())always gives exactly one value.
local function pair() return 1, 2 end
print(pair()) -- 1 2 : last item, all values
print(pair(), "end") -- 1 end: not last, one value
print("start", pair()) -- start 1 2
print((pair())) -- parentheses: one value
local t = { pair(), pair() }
print(#t) -- first call cut to 1, second expands: {1, 1, 2}
print(pair() + 10) -- in an expression: one value1 2
1 end
start 1 2
1
3
11
This rule explains a lot of surprising output. For example, print(("x"):gsub("x", "y")) prints y 1, because gsub returns two values and both reach print.
Returning a status and a result
A common Lua convention for functions that can fail is to return the result on success, or nil plus an error message on failure:
local function parseAge(text)
local n = tonumber(text)
if not n then
return nil, "not a number: " .. text
end
if n < 0 or n > 150 then
return nil, "out of range: " .. n
end
return n
end
for _, input in ipairs({ "42", "abc", "200" }) do
local age, err = parseAge(input)
if age then
print("ok", age)
else
print("error", err)
end
endok 42
error not a number: abc
error out of range: 200
io.open and many library functions follow this pattern, and assert(f()) turns it into an error when you'd rather fail loudly.
Passing results straight through
Because a call in the last position expands to all its values, you can forward results without naming them:
local function divmod(a, b)
return a // b, a % b
end
local function report(q, r)
return string.format("quotient %d, remainder %d", q, r)
end
print(report(divmod(17, 5)))
print(string.format("%d r %d", divmod(20, 6)))quotient 3, remainder 2
3 r 2
table.pack and select
To collect all return values in a table, use { f() } or table.pack(f()), which also stores the count in field n (useful when some values are nil). select(n, ...) returns everything from the n-th value on:
local function info() return "Lua", nil, 5.4 end
local packed = table.pack(info())
print(packed.n, packed[1], packed[2], packed[3])
print(select(2, "a", "b", "c"))
print(select(-1, "a", "b", "c"))
print(select("#", info()))3 Lua nil 5.4
b c
c
3
Test yourself
Given function f() return 1, 2 end, what does print(f(), 3) print?
1 2 31 331 2
What does (f()) do when f returns several values?
- Returns all of them
- Returns only the first
- Returns a table
- Raises an error
What is the usual Lua convention for a function that fails?
- Return
-1 - Return
niland an error message - Return
falseonly - Print the error and return 0