Nanfeng

Notes on software development, code, and curious ideas

Numbers and Arithmetic in Lua

Lua’s number type can contain integer and floating-point subtypes in Lua 5.3 and later. The exact representation is configurable when Lua is built; a common build uses signed 64-bit integers and double-precision floats.

1
2
3
print(math.type(3))   -- integer
print(math.type(3.0)) -- float
print(3 == 3.0) -- true

Numeric literals support decimals, exponents, and hexadecimal notation:

1
2
3
local a = 4.57e-3
local b = 0xff
local c = 0x1.8p1 -- hexadecimal float where supported

Operators

1
2
3
4
5
print(7 + 3, 7 - 3, 7 * 3)
print(7 / 3) -- floating division
print(7 // 3) -- floor division
print(7 % 3)
print(2 ^ 8)

Floor division rounds toward negative infinity, so -7 // 3 is -3. The modulo operation is defined consistently with floor division.

Use tonumber(value) for explicit conversion and math.tointeger(value) when an exact integer is required. Integer overflow may wrap according to the Lua version and build, while floating-point arithmetic has ordinary binary rounding limits:

1
print(0.1 + 0.2 == 0.3) -- often false

Compare measured floats with an application-appropriate tolerance rather than universal exact equality.

Math and randomness

The math library provides absolute value, floor, ceiling, square roots, trigonometry, logarithms, extrema, and random values. Seed a pseudo-random generator once when required by the runtime, not before every draw. Use an explicit fixed seed for reproducible tests and a cryptographically secure source for tokens, passwords, or security decisions.

Operator precedence can be subtle around unary minus and exponentiation. Parentheses are cheap documentation whenever the intended order is not immediately obvious.

+