🎓 A1Learner
🔍
0 of 47 lessons completed

Lua Return Values

A return value is a value that a function hands back to the line that called it. A Lua function can hand back several values at once.

minmax returns the small and the big

minmax compares its two numbers and returns the smaller one first. The call captures both values and prints them.

local function minmax(a, b)
  if a < b then
    return a, b
  end
  return b, a
end

local small, big = minmax(9, 4)
print(small, big)

Quotient and remainder in one return

split uses // for the whole part and % for what is left over. One call returns both numbers.

local function split(total, size)
  return total // size, total % size
end

local full, left = split(17, 5)
print(full, left)

print shows every returned value

firstLast returns two names at once. Passing the call straight to print shows both, separated by a tab.

local function firstLast()
  return "Ana", "Rey"
end

print(firstLast())

Example

local function change(amount)
  local notes = amount // 10
  local coins = amount % 10
  return notes, coins
end

local notes, coins = change(47)
print(notes, coins)

Key points

  • Return: the return statement sends values back to the caller.
  • Multiple returns: return a, b hands back two values, in that order.
  • Capture: local a, b = f() stores the returned values in variables.
  • Dropped: a returned value that no variable captures is lost.
  • Print: print(f()) prints every value the function returns, separated by tabs.

In this example, change splits 47 into tens and the rest, using // and %. It returns both numbers, the call captures them as notes and coins, and print shows 4 notes and 7 coins.

Try it Yourself

Edit the code, then press Run.

Running is simulated

Exercise

A function f() returns the values 3 and 4. Which line captures both of them?