Lua - Returning Multiple Results
A Lua function can return more than one value. Many predefined functions return multiple results like string.find() function which returns the first index of the found string and index of its end. Another important function table.unpack() function, which returns all the elements of a table separately.
Getting multiple result from predefined functions
Following code showcases the code to serialize the data.
main.lua
-- get the start and end index
-- string.find() returns nil if string not found
startIndex, endIndex = string.find("Welcome to tutorialspoint", "to")
-- print start and end indexes
print(startIndex, endIndex) --> 7 9
-- unpack an array
a, b, c = table.unpack({10, 20, 30})
-- print all variables
print(a, b, c) --> 10 20 30
Output
When we run the above code, we will get the following output−
9 10 10 20 30
Defining a custom function returning multiple values
We can define a custom function as well which can return multiple values. Consider a case, where we need to get the maximum value from an array and its index as well.
main.lua
-- function to return maximum from an array and its index
function getMax(array)
local maxIndex = 1
local maxValue = array[maxIndex]
for i,value in ipairs(array) do
if value > maxValue then
maxIndex = i
maxValue = value
end
end
-- return both values
return maxValue, maxIndex
end
-- initialize an array
array = { 12, 21, 32, 40, 55, 48, 79, 65}
-- call getMax() to get maximum from the array and its index
max, index = getMax(array)
-- print max and its index
print(max, index) -->
Output
When we run the above code, we will get the following output−
79 7
Rules on using multiple results from function
There are certain rules which we should follow while using multiple results from a function.
Multiple Assignments− variables are assigned responses. If response is not present, nil is assigned. If variable is not present, response is discarded.
Return function call− return statement returns all responses of a function.
Function call as argument− If function call is in last argument, all values are returned otherwise only one value is returned.
Functions call within constructor− If function call is the last item, all values are used otherwise only one value is used.
Functions within expression− If function call is the last in the expression, all values are used otherwise only one value is used.