Lua Multiple results


Example

Functions in Lua can return multiple results.

For example:

function triple(x)
    return x, x, x
end

When calling a function, to save these values, you must use the following syntax:

local a, b, c = triple(5)

Which will result in a = b = c = 5 in this case. It is also possible to ignore returned values by using the throwaway variable _ in the desired place in a list of variables:

local a, _, c = triple(5)

In this case, the second returned value will be ignored. It's also possible to ignore return values by not assigning them to any variable:

local a = triple(5)

Variable a will be assigned the first return value and the remaining two will be discarded.

When a variable amount of results are returned by a function, one can store them all in a table, by executing the function inside it:

local results = {triple(5)}

This way, one can iterate over the results table to see what the function returned.

Note

This can be a surprise in some cases, for example:

local t = {}
table.insert(t, string.gsub("  hi", "^%s*(.*)$", "%1")) --> bad argument #2 to 'insert' (number expected, got string)

This happens because string.gsub returns 2 values: the given string, with occurrences of the pattern replaced, and the total number of matches that occurred.

To solve this, either use an intermediate variable or put () around the call, like so:

table.insert(t, (string.gsub("  hi", "^%s*(.*)$", "%1"))) --> works. t = {"hi"}

This grabs only the first result of the call, and ignores the rest.