Learn Lua · Types · Lesson 3 of 3

Checking what you have

Data from outside often comes in more than one form: a quantity might arrive as a number, as text, or not at all. type(x) tells you which: "number", "string", "nil", "table" and so on.

LUA
type(42)      --> "number"
type("42")    --> "string"
type(nil)     --> "nil"

In the Input line, number | string | nil means any one of those.

After you test a value's type, the checker knows it inside that branch. That's called narrowing: inside if type(x) == "string" then … end, x can be used as text. tonumber turns text into a number, or gives nil if it can't.

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 = { value = "12" }

Steps

  1. Return amount: input.value as a number. Text such as "12" becomes 12, and a missing value becomes 0.
  2. Add kind: "number", "text" or "missing", for what input.value was.
  3. Text that isn't a number, such as "lots", gives an amount of 0 too.
Show a hint

Test type(input.value) and use tonumber for text: tonumber(input.value) or 0.