Type checking and conversion
type tells you what a value is, and tonumber and tostring convert between numbers and strings.
In this page:
Type checking and conversion
The type function returns one of nil, boolean, number, string, table, function, thread and userdata as a string. tonumber converts a string to a number, or returns nil when it cannot, and accepts a base as second argument. Lua also coerces automatically, so arithmetic on numeric strings works and numbers used with .. become strings.
Note:
Always check the result of tonumber for nil before using it in arithmetic.
Example: Type checking and conversion
print(type(print), type({}), type("x"), type(nil))
print(tonumber("42"), tonumber("3.5"), tonumber("abc"))
print(tonumber("ff", 16), tonumber("101", 2))
print("10" + 5, 10 .. 20)
print(tostring(true) .. "!")
-- Output:
-- function table string nil
-- 42 3.5 nil
-- 255 5
-- 15.0 1020
-- true!
Login to try C/C++/Java/PHP code in the editor
Common Mistakes
- Expecting type(nil) to return nil rather than the string "nil"
- Forgetting that tonumber returns nil for bad input
- Relying on automatic coercion and getting surprises
Chapter Summary
- type returns a string name
- tonumber returns nil on failure
- tostring converts any value
- Strings and numbers coerce in arithmetic and ..
🔒
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: