Learn Lua · Types · Lesson 2 of 3
Your own types
Name a shape once with type, then use the name wherever that shape appears:
type Line = { product: string, quantity: number }
local line: Line = { product = "Flyer", quantity = 250 }
line.quantity --> 250Every lesson's code starts this way: type Input = { … } names the shape of input,
and local input: Input = ... says that input has that shape. Types can use other
types, so in this lesson Input holds a list of Line records, and a misspelt field on
a line is reported.
A type can also list the exact values allowed. The checker then reports any other value, including a typo:
type Status = "open" | "shipped"
local status: Status = "open"
status --> "open"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 = {
shipped = false,
lines = {
{ product = "Flyer", quantity = 250 },
{ product = "Card", quantity = 10 },
},
}Steps
- Fix the misspelt status the editor marks, then return
status:"shipped"wheninput.shippedistrue, otherwise"open". - Add
summary: one line per order line, like"250 x Flyer", in order. - Add
units: the total quantity across all lines.
Show a hint
Hover over the marked line to read the error. Start status at "open", and change it
when the order has shipped. Try misspelling a field such as line.quantity too, to see
what the editor says.