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.
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.
input = { value = "12" }Steps
- Return
amount:input.valueas a number. Text such as"12"becomes 12, and a missing value becomes 0. - Add
kind:"number","text"or"missing", for whatinput.valuewas. - Text that isn't a number, such as
"lots", gives anamountof 0 too.
Show a hint
Test type(input.value) and use tonumber for text: tonumber(input.value) or 0.