Parameters and multiple return values
Lua functions can return several values at once and missing arguments are simply nil.
In this page:
Parameters and multiple return values
A function can return any number of values separated by commas. Extra arguments are dropped and missing ones become nil. When a call is used in the middle of an expression list only its first value is kept, but a call at the end of a list expands to all its values. Wrap a call in parentheses to force a single value.
Note:
Use a default with the or operator, as in name = name or "guest".
Example: Parameters and multiple return values
local function minmax(a, b)
if a < b then return a, b else return b, a end
end
local lo, hi = minmax(9, 4)
print(lo, hi)
print(minmax(1, 2), "end")
print("start", minmax(1, 2))
print((minmax(5, 3)))
local function hello(name)
name = name or "guest"
return "hi " .. name
end
print(hello(), hello("Bo"))
-- Output:
-- 4 9
-- 1 end
-- start 1 2
-- 3
-- hi guest hi Bo
Login to try C/C++/Java/PHP code in the editor
Common Mistakes
- Expecting an error when too few arguments are passed
- Expecting all return values from a call in the middle of a list
- Forgetting to capture the second return value
Chapter Summary
- Functions may return many values
- Missing arguments are nil
- Only the last call in a list expands
- (f()) keeps one value
🔒
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: