typestar

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

  1. type names one of eight basic types.
  2. tonumber returns nil on unparseable input.
  3. Strings coerce in arithmetic — convenient and risky.

Keywords and builtins used here

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.

Type this snippet

Step 3 of 3 in Control flow, step 6 of 27 in Language basics.

← Previous Next →

Types and conversion in other languages