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:

LUA
local count: number = 0
local function lineTotal(quantity: number, price: number): number
  return quantity * price
end
lineTotal(3, 2)  --> 6

The 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, or nil when 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 number
  • number | string: either a number or a string
  • integer: a whole number
  • any: any value at all, which the checker can't check for you
LUA
local total: number = 90
return "Total: " + total   -- reported: + adds numbers; .. joins text

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 = {
  lines = { { quantity = 1, price = 10 }, { quantity = 1, price = 30 } },
}

Steps

  1. Fix the type error so label is "Total: " followed by the total, such as "Total: 90".
  2. Add count: how many lines there are.
  3. 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.