Lua - Function Call as arguments
We can call functions and pass there responses as an argument in a lua function. As Lua function can return more than one value, we need to know the rules on how arguments are passed in multiple scenarios. We're using following functions in the examples discussed below:
-- returns 1 result function func1 () return 'a' end -- returns 2 results function func2 () return 'a','b' end
Case: Calling function only as an argument
If a function is called as an only argument, all responses are used. See the example below−
main.lua
-- returns 1 result function func1 () return 'a' end -- returns 2 results function func2 () return 'a','b' end function printValues(...) print(...) end -- pass a function with one returned value printValues(func1()) -- a -- pass a function with two returned value printValues(func2()) -- a b
Output
When we run the above code, we will get the following output−
a a b
Case: Calling function as last argument along with other parameters
If a function call is the last argument then all responses are used. See the example below−
main.lua
-- returns 1 result function func1 () return 'a' end -- returns 2 results function func2 () return 'a','b' end function printValues(...) print(...) end -- pass a function with one returned value printValues(1, 2, 3, func1()) -- 1 2 3 a -- pass a function with two returned value printValues(1, 2, 3, func2()) -- 1 2 3 a b
Output
When we run the above code, we will get the following output−
1 2 3 a 1 2 3 a b
Case: Calling function but not as last argument
If a function call is not the last argument, then only one response is used and other values are discarded. See the example below−
main.lua
-- returns 1 result function func1 () return 'a' end -- returns 2 results function func2 () return 'a','b' end function printValues(...) print(...) end -- pass a function with one returned value printValues(1, func1(), 2, 3, ) -- 1 a 2 3 -- pass a function with two returned value printValues(1, func2(), 2, 3, ) -- 1 a 2 3
Output
When we run the above code, we will get the following output−
1 a 2 3 1 a 2 3