Learn Lua · Errors and nil · Lesson 2 of 4

Missing values

nil means "no value". or gives a fallback when the value on its left is nil (or false):

LUA
local copies = nil
copies or 1  --> 1

Reading a field of nil is an error, so reaching deep into data that might be missing needs care. In this lesson the customer and their address might be missing, so the editor marks input.customer.address.city as a mistake. CoCoCo adds safe navigation: ?. stops and gives nil when the value before it is nil, instead of failing:

LUA
local input = ...
input.customer?.address?.city            --> nil
input.customer?.address?.city or "Unknown"  --> "Unknown"

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.

LUA
input = { customer = { email = "ada@example.test", address = { city = "Leeds" } }, copies = 5 }

Steps

  1. Return city: the customer's city from input.customer.address.city, or "Unknown" when any part is missing.
  2. Add copies: input.copies, or 1 when it is missing.
  3. Add contact: the customer's email, or their phone if there is no email, or "none".
Show a hint

Use ?. in place of each . that comes after something that might be missing. Put the fallback at the very end. or can be chained: a or b or c gives the first of them that isn't nil.