Values and Types
Type Conversion
Conversion functions turn text into numbers or values back into text.
tonumber
`tonumber` converts numeric text into a number that arithmetic can use.
Type Conversion
type_conversion.lua
Replay: real traced execution (multi-file project)
local raw = "12"
local value = tonumber(raw)
local doubled = value * 2
local label = tostring(doubled) .. " points"
print("raw=" .. raw)
print("doubled=" .. doubled)
print(label)
local raw = "7"
local value = tonumber(raw)
local doubled = value * 2
local label = tostring(doubled) .. " points"
print("raw=" .. raw)
print("doubled=" .. doubled)
print(label)
local raw = "20"
local value = tonumber(raw)
local doubled = value * 2
local label = tostring(doubled) .. " points"
print("raw=" .. raw)
print("doubled=" .. doubled)
print(label)
raw ← 12, value ← 12, doubled ← 24, label ← 24 points
1local raw→ 12 = "12" --@raw="7", "20"2local value→ 12 = tonumber(raw12)3local doubled→ 24 = value12 * 24local label→ 24 points = tostring(doubled24) .. " points"56print("raw=" .. raw12)7print("doubled=" .. doubled24)8print(label24 points)outputraw=12 doubled=24 24 points
raw ← 7, value ← 7, doubled ← 14, label ← 14 points
1local raw→ 7 = "7"2local value→ 7 = tonumber(raw7)3local doubled→ 14 = value7 * 24local label→ 14 points = tostring(doubled14) .. " points"56print("raw=" .. raw7)7print("doubled=" .. doubled14)8print(label14 points)outputraw=7 doubled=14 14 points
raw ← 20, value ← 20, doubled ← 40, label ← 40 points
1local raw→ 20 = "20"2local value→ 20 = tonumber(raw20)3local doubled→ 40 = value20 * 24local label→ 40 points = tostring(doubled40) .. " points"56print("raw=" .. raw20)7print("doubled=" .. doubled40)8print(label40 points)outputraw=20 doubled=40 40 points
Follow the Conversion
rawstarts as"12".tonumber(raw)gives the number12.doubled = value * 2becomes24.labelbecomes24 points.- The program prints
raw=12,doubled=24, and24 points. | raw | doubled | label | | --- | --- | --- | | 7 | 14 | 14 points | | 12 | 24 | 24 points | | 20 | 40 | 40 points |
Exercise: type_conversion.lua
Reproduce 24 points, then use raw 7 and 20 to predict each doubled value and label.