Functions and Scope
Multiple Returns
Lua functions can return more than one value.
several results
Assign each returned value to its own local name when both results matter.
Multiple Returns
multiple_returns.lua
Replay: real traced execution (multi-file project)
local total = 8
local function split_total(value)
local left = value / 2
local right = value - left
return left, right
end
local first, second = split_total(total)
print("total=" .. total)
print("first=" .. first)
print("second=" .. second)
local total = 6
local function split_total(value)
local left = value / 2
local right = value - left
return left, right
end
local first, second = split_total(total)
print("total=" .. total)
print("first=" .. first)
print("second=" .. second)
local total = 12
local function split_total(value)
local left = value / 2
local right = value - left
return left, right
end
local first, second = split_total(total)
print("total=" .. total)
print("first=" .. first)
print("second=" .. second)
total ← 8
1local total→ 8 = 8 --@total=6, 1223local function split_total(value)4 local left = value / 25 local right = value - left6 return left, right7end89local first, second = split_total(total8)first ← 4.0, second ← 4.0
9local first→ 4.0, second→ 4.0 = split_total(total8)1011print("total=" .. total8)12print("first=" .. first4.0)13print("second=" .. second4.0)outputtotal=8 first=4.0 second=4.0
total ← 6
1local total→ 6 = 623local function split_total(value)4 local left = value / 25 local right = value - left6 return left, right7end89local first, second = split_total(total6)first ← 3.0, second ← 3.0
9local first→ 3.0, second→ 3.0 = split_total(total6)1011print("total=" .. total6)12print("first=" .. first3.0)13print("second=" .. second3.0)outputtotal=6 first=3.0 second=3.0
total ← 12
1local total→ 12 = 1223local function split_total(value)4 local left = value / 25 local right = value - left6 return left, right7end89local first, second = split_total(total12)first ← 6.0, second ← 6.0
9local first→ 6.0, second→ 6.0 = split_total(total12)1011print("total=" .. total12)12print("first=" .. first6.0)13print("second=" .. second6.0)outputtotal=12 first=6.0 second=6.0
Follow the Two Results
totalstarts as8.split_total(total)receives8.leftbecomes8 / 2, which prints as4.0.rightbecomes8 - 4.0, which also prints as4.0.- Lua returns both values, so
first=4.0andsecond=4.0. | total | first | second | | --- | --- | --- | | 8 | 4.0 | 4.0 | | 6 | 3.0 | 3.0 | | 12 | 6.0 | 6.0 |
Exercise: multiple_returns.lua
Reproduce total=8, first=4.0, and second=4.0, then use the pinned total variants 6 and 12 to predict first=3.0 second=3.0 and first=6.0 second=6.0.