Returning More Than One Value
A Lua function can return more than one value. Write the values after return, separated by commas:
function divide(a, b)
return a // b, a % b
end
local q, r = divide(17, 5)
print("quotient:", q)
print("remainder:", r)
Output:
quotient: 3
remainder: 2
divide returns two values: the result of whole-number division and the remainder. To catch both, list two variables before the =. The first variable gets the first value, and the second gets the second. This is the same rule as local lives, level = 3, 1 from the variables lesson.
The quotient and remainder belong together, so one function that returns both is a natural fit.
Catching fewer or more values
You do not have to catch every value. If you list fewer variables, the extra values are dropped. If you list more, the extra variables get nil:
local onlyQ = divide(17, 5)
print(onlyQ)
local x, y, z = divide(17, 5)
print(x, y, z)
Output:
3
3 2 nil
onlyQ got the 3, and the 2 was thrown away. z had no value to catch, so it is nil.
Passing all the values on
When the call is the last argument of another call, such as print, all the returned values are passed along. When it is not the last argument, only the first value is kept:
print(divide(9, 2))
print(divide(9, 2), "end")
Output:
4 1
4 end
In the second line, "end" comes after the call, so only the 4 is passed to print.
When to return several values
Return several values when they are two parts of one answer: a quotient and a remainder, or the smaller and larger of two numbers. If the values are not related, two separate functions are easier to read.
Lua's own functions use this a lot. string.find, which you will meet in the Standard Library section, returns both where a match starts and where it ends.
In the exercise, complete a function that returns two numbers with the smaller one first.