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
return "silver chalice", 45, truesends three at once.select("#", ...)counts;select(2, ...)skips.- Wrapping a call in parentheses keeps only the first value.
Keywords and builtins used here
endfunctionhaullocalopen_chestprintreturnselecttostring
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.
Step 2 of 3 in Functions, step 12 of 27 in Language basics.