Learn Lua · Types · Lesson 1 of 3
Type annotations
Every script is type-checked before it runs: CoCoCo works out what kind of value each name holds and reports mistakes, such as adding text to a number, with the line they're on. You can also say what you expect, with a colon after a name:
local count: number = 0
local function lineTotal(quantity: number, price: number): number
return quantity * price
end
lineTotal(3, 2) --> 6The annotations catch mistakes at the place you made them, and they tell the next reader what a function takes and gives back.
The Input lines at the top of each lesson use a few more forms:
string?: a string, ornilwhen it's missing{ string }: a list of strings{ name: string, total: number }: a record with those fields{ [string]: number }: a record with any field names, each holding a numbernumber | string: either a number or a stringinteger: a whole numberany: any value at all, which the checker can't check for you
local total: number = 90
return "Total: " + total -- reported: + adds numbers; .. joins textWhat 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 = {
lines = { { quantity = 1, price = 10 }, { quantity = 1, price = 30 } },
}Steps
- Fix the type error so
labelis"Total: "followed by the total, such as"Total: 90". - Add
count: how many lines there are. - Add
average: the total divided by the number of lines, or 0 when there are no lines.
Show a hint
The error is on the label line: join text with .., not +. Check for zero lines before dividing.