Skip to content
AgileLogics
5 min read

Numbers and Math

Prerequisites: Data types

Since Lua 5.3, numbers are either integers or floats; both have the type number.

print(7 + 2)
print(7 - 2)
print(7 * 2)
print(7 / 2)
print(8 / 2)
print(7 // 2)
print(7 % 2)
print(2 ^ 10)
print(-7 // 2)
9
5
14
3.5
4.0
3
1
1024.0
-4
  • / always gives a float: 8 / 2 is 4.0.
  • // is floor division — it rounds down, so -7 // 2 is -4.
  • ^ is exponentiation and always gives a float.

Integers vs floats

print(math.type(3))
print(math.type(3.0))
print(3 == 3.0)
print(math.tointeger(3.0))
print(math.floor(3.7))
print(math.maxinteger)
print(math.maxinteger + 1 == math.mininteger)
integer
float
true
3
3
9223372036854775807
true

Integers are 64-bit and wrap around on overflow. Lua 5.1 and LuaJIT have only floats (no //, math.type, or integer division).

The math library

print(math.sqrt(16))
print(math.abs(-3.5))
print(math.max(4, 9, 2))
print(math.min(4, 9, 2))
print(math.ceil(2.1))
print(math.floor(-2.5))
print(string.format("%.4f", math.pi))
print(string.format("%.2f", math.pi))
print(math.huge)
4.0
3.5
9
2
3
-3
3.1416
3.14
inf

There's no math.round; use math.floor(x + 0.5) for positive numbers, or string.format("%.0f", x) for display.

Printing a float directly shows 14 significant digits in Lua 5.4 (3.1415926535898) but full precision in Lua 5.5 (3.1415926535897931), so use string.format whenever the exact output matters.

Random numbers

math.randomseed(42)
print(math.random(1, 6))
print(math.random(1, 6))
local r = math.random()
print(r >= 0 and r < 1)
6
2
true

math.random(m, n) returns an integer from m to n; math.random() a float in [0, 1). Seeding with a fixed number repeats the same sequence — handy for tests. Lua 5.4 seeds randomly at startup, so without randomseed each run differs.

Practice

A pizza has 8 slices shared by 3 people. Print how many whole slices each person gets, how many are left over, and each share with 2 decimals.

Show solution
local slices, people = 8, 3
print(slices // people)
print(slices % people)
print(string.format("%.2f", slices / people))
2
2
2.67