Functions and Scope
Return Values
return sends a computed value back to the caller.
computed result
Store the returned value when later code needs to use or print it.
Return Values
return_values.lua
Replay: real traced execution (multi-file project)
local width = 4
local function area(side)
return side * side
end
local result = area(width)
print("width=" .. width)
print("area=" .. result)
local width = 2
local function area(side)
return side * side
end
local result = area(width)
print("width=" .. width)
print("area=" .. result)
local width = 7
local function area(side)
return side * side
end
local result = area(width)
print("width=" .. width)
print("area=" .. result)
width ← 4
1local width→ 4 = 4 --@width=2, 723local function area(side)4 return side * side5end67local result = area(width4)result ← 16
7local result→ 16 = area(width4)89print("width=" .. width4)10print("area=" .. result16)outputwidth=4 area=16
width ← 2
1local width→ 2 = 223local function area(side)4 return side * side5end67local result = area(width2)result ← 4
7local result→ 4 = area(width2)89print("width=" .. width2)10print("area=" .. result4)outputwidth=2 area=4
width ← 7
1local width→ 7 = 723local function area(side)4 return side * side5end67local result = area(width7)result ← 49
7local result→ 49 = area(width7)89print("width=" .. width7)10print("area=" .. result49)outputwidth=7 area=49
Follow the Return
widthstarts as4.- The call is
area(width). - Inside the function,
sidereceives4. - The function returns
side * side, which is16. - The caller stores that value in
result. | width | calculation | returned area | | --- | --- | --- | | 4 |4 * 4| 16 | | 2 |2 * 2| 4 | | 7 |7 * 7| 49 |
Exercise: return_values.lua
Reproduce width=4 and area=16, then use the pinned width variants 2 and 7 to predict area=4 and area=49.