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

width
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)
  1. width ← 4

    1local width→ 4 = 4 --@width=2, 723local function area(side)4  return side * side5end67local result = area(width4)
  2. result ← 16

    7local result→ 16 = area(width4)89print("width=" .. width4)10print("area=" .. result16)
    outputwidth=4
    area=16
  1. width ← 2

    1local width→ 2 = 223local function area(side)4  return side * side5end67local result = area(width2)
  2. result ← 4

    7local result→ 4 = area(width2)89print("width=" .. width2)10print("area=" .. result4)
    outputwidth=2
    area=4
  1. width ← 7

    1local width→ 7 = 723local function area(side)4  return side * side5end67local result = area(width7)
  2. result ← 49

    7local result→ 49 = area(width7)89print("width=" .. width7)10print("area=" .. result49)
    outputwidth=7
    area=49

Follow the Return

  1. width starts as 4.
  2. The call is area(width).
  3. Inside the function, side receives 4.
  4. The function returns side * side, which is 16.
  5. 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.