Lua - Function Calls within Expressions
We can have function calls within expresssions. But if a function is returning multiple values, then we should know the rule while using them in expressions. Lua adjusts the number of responses to one so that only first value is used in the expression.
Case: Function call in an Expression as last operand
If a function call is in an expression than multiple values will not be used. Lua will adjust the responses to one value. In this example, we're placing function call as last operand. See the example below−
main.lua
-- returns 2 results
function func2 ()
return 'a','b'
end
-- expression concatenating x with response of func2()
print ('x' .. func2())
Output
When we run the above code, we will get the following output−
xa
Case: Function call in an Expression but not as last operand
If a function call is in an expression than multiple values will not be used. Lua will adjust the responses to one value. In this example, we're placing function call as last operand. See the example below−
main.lua
-- returns 2 results function func2 () return 'a','b' end -- expression concatenating response of func2() with x print (func2().. 'x')
Output
When we run the above code, we will get the following output−
xa
Case: Function call in middle
Following is an another example where we're having a simple addition expression to add few numbers with response of function call. See the example below−
main.lua
-- returns 2 results function func2 () return 1, 2, 3 end -- expression adding numbers with first response of function -- 4 + 1 + 5 = 10 sum = 4 + func2() + 5 -- print sum print (sum)
Output
When we run the above code, we will get the following output−
10