Working with Numbers in Lua

The first data type we will look at is number. Numbers are used to represent quantities or amounts, and are also used in some control structures and to retrieve values from tables.

Whereas many languages differentiate between integer and floating point numbers, Lua treats all numbers as double-precision floating-point numbers.

Lua is quite flexible about how numbers are formatted, accepts most common floating-point formats, and will even automatically convert strings to numbers when performing arithmetic operations:

-- integer
print(123) -- 123

-- floating point
print(1.23) -- 1.23
print(0.0456) -- 0.0456

-- exponential
print(0.123e+3) -- 123.0
print(123e-3) -- 0.123
print(4.56E2) -- 456.0

-- hexadecimal
print(0x00) -- 0
print(0x7B) -- 123
print(0xff) -- 255

--strings
print("120" + 3) -- 123
print("0x78" + 3) -- 123

We will see a bit more about working with numbers in the arithmetic operations section.