Lua Numbers
Lua has one number type with two internal representations: 64-bit integers and double-precision floats. Most of the time you don't need to care which one you have; Lua picks a sensible result for each operation.
local apples = 12 -- integer
local price = 0.35 -- float
local total = apples * price
print(apples, price, total)
print(math.type(apples), math.type(total))12 0.35 4.2
integer float
Writing numbers
| Literal | Meaning | Subtype |
|---|---|---|
42 |
decimal | integer |
3.0, .5, 2. |
decimal with a point | float |
1e3, 2.5E-2 |
scientific notation | float |
0xFF, 0x1A |
hexadecimal | integer |
0x1p4 |
hexadecimal float (1 × 2⁴) | float |
print(42, 3.0, .5, 1e3, 2.5E-2)
print(0xFF, 0x1A, 0x1p4)42 3.0 0.5 1000.0 0.025
255 26 16.0
Notice that floats always print with a decimal point (3.0, 1000.0), which helps you see the subtype.
Arithmetic operators
| Operator | Meaning | 7 op 2 |
|---|---|---|
+ |
addition | 9 |
- |
subtraction | 5 |
* |
multiplication | 14 |
/ |
float division | 3.5 |
// |
floor division | 3 |
% |
modulo (remainder) | 1 |
^ |
exponentiation (always float) | 49.0 |
- (unary) |
negation | -7 |
local a, b = 7, 2
print(a + b, a - b, a * b)
print(a / b, a // b, a % b)
print(a ^ b, -a)9 5 14
3.5 3 1
49.0 -7
Floor division and modulo with negatives
// rounds down (towards minus infinity), not towards zero. % is defined so that a == (a // b) * b + a % b, which means the result has the sign of the divisor:
print(-7 // 2, -7 % 2)
print(7 // -2, 7 % -2)
print(7.5 // 2, 7.5 % 2)-4 1
-4 -1
3.0 1.5
This is handy: x % n with a positive n is always between 0 and n - 1, perfect for wrapping around an index in a circular list.
Precision of floats
Floats can't represent most decimal fractions exactly. print shows 14 significant digits, which hides tiny errors, but comparisons still see them:
local sum = 0.1 + 0.2
print(sum)
print(sum == 0.3)
print(string.format("%.17g", sum))
print(math.abs(sum - 0.3) < 1e-9)0.3
false
0.30000000000000004
true
Tip: Never compare floats with
==after arithmetic. Compare the difference with a small tolerance, or store money as integer cents.
Special float values
Dividing a float by zero doesn't raise an error. It gives infinity or "not a number" (NaN):
print(1 / 0, -1 / 0)
print(math.huge == 1 / 0)
local nan = 0 / 0
print(nan ~= nan)inf -inf
true
true
NaN is the only value that is not equal to itself, which is the standard way to test for it. Integer division by zero, on the other hand, is an error: 1 // 0 fails with "attempt to perform 'n//0'".
Test yourself
What does print(10 / 2) show?
55.05.00- An error
What is -7 // 2?
-3-4-3.53
What is 2 ^ 3?
88.061(XOR)