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

total
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)
  1. 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)
  2. 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
  1. 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)
  2. 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
  1. 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)
  2. 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

  1. total starts as 8.
  2. split_total(total) receives 8.
  3. left becomes 8 / 2, which prints as 4.0.
  4. right becomes 8 - 4.0, which also prints as 4.0.
  5. Lua returns both values, so first=4.0 and second=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.