Return Values

Values are returned by functions using the return statement, optionally followed by a value or a comma-separated sequence of two or more values. Let's take a quick at how this works with the following function definition which returns two values:

local two = function()
return 1, 2
end

We can collect both return values by defining variables for each expected value:

local a, b = two()

print(a) -- 1
print(b) -- 2

Unlike some programming languages, it is not an error to collect a different number of values than the function returns. If we only assign one of the return values to a variable, the left-most return value is assigned, while the others are simply ignored:

local a = two()

print(a) -- 1
print(b) -- nil

Likewise, if we assign more values to variables than are returned by the function, the extra variables are simply assigned a value of nil:

local a, b, c = two()

print(a) -- 1
print(b) -- 2
print(c) -- nil