0Pricing
Lua Academy · Lesson

Multiple Return Values

Return and capture multiple values from a single function call.

Multiple Return Values is a free Lua Academy lesson on CoddyKit — lesson 2 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the Lua Academy learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.

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)

Middle Position Adjustment

When a function call appears in the middle of an expression list (not the last position), Lua truncates it to a single value. Only the last expression in the list can produce multiple values.

local function pair()
  return 1, 2
end

-- pair() in middle: only 1 value used
local t = {pair(), pair()}
print(#t, t[1], t[2], t[3])  -- 3  1  1  2
-- first pair() gives just 1; last pair() gives 1,2

-- pair() at end: all values used
local t2 = {10, pair()}
print(#t2, t2[1], t2[2], t2[3])  -- 3  10  1  2

Parentheses Force Single Value

Wrapping a function call in parentheses forces it to return exactly one value. This is useful when you want only the first return value regardless of how many the function produces.

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

print(coords())    -- 10  20  30  (all three)
print((coords()))  -- 10  (parentheses: single value only)

local x = (coords())
print(x)           -- 10

string.find Return Values

Many standard library functions use multiple returns. string.find returns start and end positions of a match (plus captures). math.modf returns integer and fractional parts. Understanding these patterns helps you use the standard library fluently.

local s = "hello world"
local start, finish = string.find(s, "world")
print(start, finish)   -- 7  11

-- math.modf: integer and fractional parts
local int, frac = math.modf(3.75)
print(int, frac)       -- 3   0.75

Capturing with table.pack

table.pack(...) captures all arguments (or return values via ...) into a table. The table includes a field n with the total count, including nil values. This preserves the exact count unlike # which stops at the first hole.

local function getData()
  return "Alice", 30, nil, true
end

local t = table.pack(getData())
print(t.n)         -- 4
print(t[1])        -- Alice
print(t[2])        -- 30
print(t[3])        -- nil
print(t[4])        -- true

table.unpack for Spreading

table.unpack(t, i, j) returns the elements of a table as individual values. It is the inverse of table.pack. Use it to pass a table's contents as arguments to a function, or to spread values in a return statement.

local args = {10, 20, 30}

local function sum3(a, b, c)
  return a + b + c
end

print(sum3(table.unpack(args)))  -- 60

-- Use in return
local function passThrough(t)
  return table.unpack(t)
end
print(passThrough({5, 6, 7}))   -- 5  6  7

Error-Style Returns

A common Lua convention is to return nil, errorMessage on failure and the result on success. Callers check the first return value: if nil, an error occurred. This avoids exceptions for expected failure cases.

local function openConfig(path)
  local f = io.open(path, "r")
  if not f then
    return nil, "cannot open: " .. path
  end
  local content = f:read("*a")
  f:close()
  return content
end

local data, err = openConfig("config.lua")
if not data then
  print("Error:", err)
end

Swapping with Multiple Returns

Multiple return values elegantly solve the swap problem. The right-hand side is evaluated before assignment, so a, b = b, a correctly exchanges values without a temporary variable.

local a, b = 5, 10
print(a, b)   -- 5  10

a, b = b, a
print(a, b)   -- 10  5

-- Works for three-way rotation too
local x, y, z = 1, 2, 3
x, y, z = z, x, y
print(x, y, z)  -- 3  1  2

pcall Return Convention

pcall(f, ...) itself uses multiple returns: the first value is a boolean (true on success, false on error), and subsequent values are either the return values of f or the error message. Always check the first return before using the rest.

local function risky(x)
  if x < 0 then error("negative input") end
  return math.sqrt(x)
end

local ok, result = pcall(risky, 16)
print(ok, result)   -- true  4.0

ok, result = pcall(risky, -1)
print(ok, result)   -- false  input:2: negative input

Quick Check

What does print((string.find("hello", "ll"))) output?

Recap: Multiple Return Values

Key takeaways:

  • Return multiple values: return a, b, c
  • Extra values discarded; missing become nil
  • Middle-position calls are truncated to 1 value
  • (f()) forces exactly 1 value
  • table.pack/table.unpack for dynamic value lists
  • Convention: return nil, errmsg on failure

Frequently asked questions

Is the “Multiple Return Values” lesson free?

Yes — the full text of “Multiple Return Values” is free to read here on the web, and the Lua Academy course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the Lua Academy course, upgrade to CoddyKit PRO.

What will I learn in “Multiple Return Values”?

Return and capture multiple values from a single function call. You practise Lua Academy with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.

Do I need any experience to start Lua Academy?

No prior experience is required. Lua Academy on CoddyKit is structured for beginners through advanced learners; this is — lesson 2 of 4, so you can start here or from the beginning and move at your own pace.

How long does the “Multiple Return Values” lesson take?

Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.

Can I write and run code in this Lua Academy lesson?

Yes. Every Lua Academy lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.

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