Learn Lua · Errors and nil · Lesson 3 of 4
Several results
A function can return more than one value. Separate them with commas, and receive them with a comma-separated list of names:
local function minMax(a, b)
if a < b then return a, b end
return b, a
end
local low, high = minMax(9, 4)
low --> 4
high --> 9string.match does this too: with two bracketed parts in the pattern, it returns two
values. (%a+) (%a+) means two words with a space between. When the text doesn't
match, it returns nil instead, and the checker won't let you use a value that might be
nil as text until you've checked it.
What your code receives
Your code gets its data as input. The type Input line at the top of the code lists every field, and the editor uses it to suggest field names and spot typos. Here is an example. Each check sends different values, so work from the fields rather than these exact values.
input = { name = "Ada Lovelace" }Steps
- Return
first: the first name frominput.name, such as"Ada"from"Ada Lovelace". - Add
last: the last name. - Add
initials: the first letter of each, like"A. L.".
Show a hint
Receive both names at once: local first, last = …. If either is nil, stop with an
error. After that check, the editor knows both are text, and :sub(1, 1) gives a first
letter.