Lua - Handling Multiple Assignment



A Lua function can return more than one value. Now knowing assignment rules, we can utilize this Lua feature efficiently. 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 - Same Responses as Variables

If a function responses are assigned to same number of variables, then values are assigned respectively. See the example below−

main.lua

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

-- case matching arguments
x = func2()          -- x='a', 'b' is discarded
print(x)
x,y = func2()        -- x='a', y='b'
print(x, y)
x,y,z = 10,func2()   -- x=10, y='a', z='b'
print(x, y, z)

Output

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

a	b
10	a	b

Example - Less Responses than Variables

If a function responses are assigned to more number of variables, then values are assigned respectively and other are assigned nil. 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 

-- case no response
x,y = func0()      -- x=nil, y=nil
print(x, y)
x,y = func1()      -- x='a', y=nil
print(x, y)
x,y,z = func2()    -- x='a', y='b', z=nil
print(x, y, z)

Output

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

a	nil
a	b	nil

Example - function call not the last element

If a function call is not last element then only first response is returned. See the example below−

main.lua

-- returns no results
function func0 () 
end

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

-- case function call not the last element
x,y = func2(), 20      -- x='a', y=20
print(x, y)
x,y = func0(), 20, 30  -- x=nil, y=20, 30 is discarded
print(x, y)

Output

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

a	20
nil	20

Example - function call is the last element

If a function call is last element then all responses are returned. See the example below−

main.lua

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

-- case function call being last element, all responses are used
print(func2())          --  a   b
print(func2(), 1)       --  a   1
print(func2() .. "x")   --  ax   

Output

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

a	b
a	1
ax
lua_function_multiple_results.htm
Advertisements