Lua - Function Call in Constructors



We can call functions in a Lua constructor. As Lua function can return more than one value, we can utilize this feature to initialize an element like array with values returned from a function. 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   

Case: Calling function only within constructor

If a function responses are used within constructor functions, all responses are used. 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


array = {func0()}         -- array = {}  (an empty table)

-- print length of array
print(#array)             -- 0

array = {func1()}         -- array = {'a'}
-- print length of array
print(#array)             -- 1

for _, v in ipairs(array) do
   print(v)
end

array = {func2()}         -- array = {'a', 'b'}
-- print length of array
print(#array)             -- 2

for _, v in ipairs(array) do
   print(v)
end

Output

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

0
1
a
2
a
b

Case: Calling function as last argument within constructor

If a function call is done as last argument within constructor functions, then all responses are used. 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


array = {'z', func0()}         -- array = {'z'} 

-- print length of array
print(#array)             -- 1

array = {'z', func1()}         -- array = {'z','a'}
-- print length of array
print(#array)             -- 2

for _, v in ipairs(array) do
   print(v)
end

array = {'z', func2()}         -- array = {'z', 'a', 'b'}
-- print length of array
print(#array)             -- 2

for _, v in ipairs(array) do
   print(v)
end

Output

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

1
2
z
a
3
z
a
b

Case: Calling function but not as last argument within constructor

If a function call is not the last argument within constructor functions, then only one response is used and other values are discarded. See the example below−

main.lua

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

array = {func2(), 'z', }         -- array = {'a', 'z'}
-- print length of array
print(#array)             -- 2

for _, v in ipairs(array) do
   print(v)
end

Output

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

2
a
z
lua_function_multiple_results.htm
Advertisements