Lua - Return Function Call



A return statement in Lua returns all the values returned by a function call.

As we can return any number of values from a function, using return statement clubbed with function calls, we can even return different numbers of values as per the logic. We're using following functions in the examples discussed below:

-- returns no results
function func0 () 
end                  

-- returns 1 result
function func1 () 
   return 'a' 
end       

-- returns 2 results
function func2 () 
   return 'a','b' 
end   

Example - Return different number of values

Based on the logic, a function can return different number of values. For example, a function can return nothing, one value or more values based on the parameter passed. See the example below−

main.lua

-- returns no results
function func0 () 
end                  

-- returns 1 result
function func1 () 
   return 'a' 
end       

-- returns 2 results
function func2 () 
   return 'a','b' 
end

-- function to return 2, 1 or 0 value based on value of i passed
function funcVariableReturns(i)
   if i == 2 then
      return func2()  -- return 2 values
   elseif i == 1 then
      return func1()  -- return 1 value
   else
      return func0()  -- nothing is returned.
   end
end

print(funcVariableReturns(0))  -- no value
print(funcVariableReturns(1))  -- 1 value 'a'
print(funcVariableReturns(2))  -- 2 values 'a', 'b'
print(funcVariableReturns(3))  -- no value

Output

When we run the above code, we will get the following output−

a
a	b

Example - Forcing a function to return a single value

We can force a function call to return only one value by enclosing the function call in () brackets. See the example below−

main.lua

-- returns 2 results
function func2 () 
   return 'a','b' 
end

-- normal execution
x, y = func2()
print(x, y)        -- 'a', 'b'

-- restricted execution with enclosing brackets
x1, y1 = (func2())
print(x1, y1)      -- 'a', nil

Output

When we run the above code, we will get the following output−

a	b
a	nil
lua_function_multiple_results.htm
Advertisements