0Pricing
Lua Academy · Lesson

Type Coercion and Conversion

Learn automatic coercion between strings and numbers, and explicit tonumber/tostring.

What Is Type Coercion?

Type coercion is the automatic conversion of a value from one type to another when the context requires it. Lua performs coercion in two specific directions: string-to-number in arithmetic contexts, and number-to-string in concatenation contexts.

Unlike JavaScript, Lua coercion is narrow and predictable. It does not coerce booleans to numbers or tables to strings automatically.

-- String to number (arithmetic context)
print("10" + 5)     -- 15  (coerced)
print("3.14" * 2)   -- 6.28

-- Number to string (concatenation context)
print(10 .. "px")   -- 10px
print(3.14 .. "!")  -- 3.14!

-- No boolean coercion
-- print(true + 1)  -- ERROR!

String-to-Number Coercion Rules

When a string appears in an arithmetic expression, Lua tries to convert it to a number. If the string doesn't represent a valid number, a runtime error is raised. Valid numeric strings include integers ("42"), floats ("3.14"), hex ("0xff"), and scientific notation ("1e3").

Strings with leading/trailing whitespace are accepted — Lua trims them during coercion.

print("42" + 0)      -- 42    (integer)
print("3.14" + 0)    -- 3.14  (float)
print("0xff" + 0)    -- 255   (hex)
print("  10  " + 0)  -- 10    (whitespace ok)
print("1e3" + 0)     -- 1000.0

-- This will error:
-- print("hello" + 0)  -- attempt to perform arithmetic on a string value

All lessons in this course

  1. Lua Data Types Overview
  2. Declaring Variables in Lua
  3. Arithmetic and Relational Operators
  4. Type Coercion and Conversion
← Back to Lua Academy