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):
local copies = nil
copies or 1 --> 1Reading 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:
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.
input = { customer = { email = "ada@example.test", address = { city = "Leeds" } }, copies = 5 }Steps
- Return
city: the customer's city frominput.customer.address.city, or"Unknown"when any part is missing. - Add
copies:input.copies, or 1 when it is missing. - Add
contact: the customer'semail, or theirphoneif 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.