0Pricing
Lua Academy · Lesson

Multiple Return Values

Return and capture multiple values from a single function call.

Returning Multiple Values

Unlike most languages, Lua functions can natively return multiple values from a single return statement. Multiple values are comma-separated after return. This avoids the need for wrapper objects or output parameters.

local function divmod(a, b)
  return math.floor(a / b), a % b
end

local quotient, remainder = divmod(17, 5)
print(quotient, remainder)   -- 3  2

Adjusting Return Values

Lua adjusts return values to match the number of receivers. Extra values are discarded; missing values become nil. This adjustment happens whenever a function call is not the last expression in a list — in that position, only the first value is kept.

local function triple()
  return 10, 20, 30
end

local a, b, c = triple()
print(a, b, c)      -- 10  20  30

local x, y = triple()
print(x, y)         -- 10  20  (30 discarded)

local p = triple()
print(p)            -- 10  (only first when 1 var)

All lessons in this course

  1. Defining and Calling Functions
  2. Multiple Return Values
  3. Varargs and the ... Operator
  4. Recursion in Lua
← Back to Lua Academy