← Back to Lua Course | Chapter 2: Variables & Types | Lesson 6 of 7

Type checking and conversion

type tells you what a value is, and tonumber and tostring convert between numbers and strings.

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

lua
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!
Common Mistakes
  1. Expecting type(nil) to return nil rather than the string "nil"
  2. Forgetting that tonumber returns nil for bad input
  3. 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:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.