Types and conversion in Lua
type inspects; tostring and tonumber convert explicitly.
-- type inspects; tostring and tonumber convert explicitly.
print(type("rope"), type(42), type(nil), type(print))
local roll = "17"
print(tonumber(roll) + 3)
print(tonumber("torch"))
-- Strings holding numbers coerce in arithmetic, a mixed blessing.
print("8" + 1)
print(8 .. " damage")
-- tostring makes anything printable, tables by address.
print(tostring(true))
local chest = {}
print(tostring(chest):sub(1, 5) .. "...")
How it works
typenames one of eight basic types.tonumberreturns nil on unparseable input.- Strings coerce in arithmetic — convenient and risky.
Keywords and builtins used here
localprintsubtonumbertostringtype
The run, in numbers
- Lines
- 15
- Characters to type
- 427
- Tokens
- 89
- Three-star pace
- 65 tpm
At the three-star pace of 65 tokens a minute, this run takes about 82 seconds.
Step 3 of 3 in Control flow, step 6 of 27 in Language basics.