← Back to Lua Course | Chapter 5: Functions | Lesson 2 of 7

Parameters and multiple return values

Lua functions can return several values at once and missing arguments are simply nil.

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

lua
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
Common Mistakes
  1. Expecting an error when too few arguments are passed
  2. Expecting all return values from a call in the middle of a list
  3. 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

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.