typestar

Multiple returns in Lua

Functions return several values; parentheses truncate to one.

-- Functions return several values; callers unpack them in place.
local function open_chest()
  return "silver chalice", 45, true
end

local item, value, trapped = open_chest()
print(string.format("%s worth %d (trapped: %s)",
  item, value, tostring(trapped)))

-- select counts and skips; extra returns vanish when unwanted.
local function haul()
  return "rope", "idol", "map"
end
print("Haul size: " .. select("#", haul()))
print("Skipping one: " .. select(2, haul()))
local first_only = (haul())
print("Parentheses keep just: " .. first_only)

How it works

  1. return "silver chalice", 45, true sends three at once.
  2. select("#", ...) counts; select(2, ...) skips.
  3. Wrapping a call in parentheses keeps only the first value.

Keywords and builtins used here

The run, in numbers

Lines
17
Characters to type
540
Tokens
97
Three-star pace
65 tpm

At the three-star pace of 65 tokens a minute, this run takes about 90 seconds.

Type this snippet

Step 2 of 3 in Functions, step 12 of 27 in Language basics.

← Previous Next →

Multiple returns in other languages