Multiple Return Values in Lua

Lua has support for multiple return values. This feature is commonly used in idiomatic Lua, for example, to return both result and error values from a function.

-- The function signature in Lua doesn't specify return types,
-- but we can return multiple values simply by listing them.
function vals()
    return 3, 7
end

-- In the main part of our script
-- Here we use the 2 different return values from the
-- call with multiple assignment.
local a, b = vals()
print(a)
print(b)

-- If you only want a subset of the returned values,
-- you can simply omit the variables you don't need.
local _, c = vals()
print(c)

To run the program, save it as multiple_return_values.lua and use the lua command:

$ lua multiple_return_values.lua
3
7
7

In Lua, functions can return any number of values, and multiple assignment allows you to easily capture these values. If you don’t need all the returned values, you can simply omit the variables for the ones you don’t need, which is similar to using the blank identifier in other languages.

Returning multiple values is another nice feature of Lua functions; we’ll explore more Lua features in the upcoming examples.