Skip to content

Lua Numbers Guide — Arithmetic, Math Library, and Numeric Precision

DodaTech Updated 2026-06-28 2 min read

In this tutorial, you will learn about Lua Numbers Guide. We cover key concepts, practical examples, and best practices to help you master this topic.

Lua numbers are double-precision floating point values by default (64-bit IEEE 754) with optional 64-bit integers in Lua 5.3+, providing versatile numeric computation through a compact set of operators and the math library.

Number Types

local pi = 3.14159
local integer = 42
local hex = 0xFF        --> 255
local octal = 0o77      --> 63
local binary = 0b1010   --> 10
local huge = math.huge  --> inf

Arithmetic Operators

print(10 + 5)    --> 15
print(10 - 5)    --> 5
print(10 * 5)    --> 50
print(10 / 3)    --> 3.3333333333333
print(10 // 3)   --> 3  (integer division)
print(10 % 3)    --> 1
print(10 ^ 2)    --> 100

Math Library

print(math.floor(3.7))  --> 3
print(math.ceil(3.2))   --> 4
print(math.sqrt(144))   --> 12.0
print(math.sin(math.pi/2))  --> 1.0
print(math.random(1, 100))  --> random number

Common Mistakes

1. Assuming integer division

10 / 3 returns float 3.333. Use 10 // 3 for integer division.

2. Floating point precision

0.1 + 0.2 ~= 0.3 due to IEEE 754. Compare with tolerance: math.abs(a - b) < 1e-10.

3. Math.random not seeded

Always call math.randomseed(os.time()) once before using math.random.

Practice Questions

1. What does 10 / 3 return? 3.3333333333333 (float, not integer).

2. How do you get integer division in Lua 5.3+? Use // operator: 10 // 3 returns 3.

3. What is math.huge? A special value representing infinity, used for comparisons and overflow detection.

FAQ

{{< faq question="Does Lua have integers?" >}} Lua 5.3+ has 64-bit integers. Earlier versions use only floating point. Check with math.type(x) which returns "integer" or "float". {{< /faq >}}

{{< faq question="How do I convert a string to a number?" >}} Use tonumber("42") which returns the number or nil if invalid. For formatting numbers to strings, use string.format("%.2f", 3.14159). {{< /faq >}}

{{< faq question="What is the range of Lua numbers?" >}} Doubles handle approximately 1e-308 to 1e+308 with about 15-17 significant digits. Integers are 64-bit signed: -2^63 to 2^63-1. {{< /faq >}}

{{< faq question="How do I generate random numbers?" >}} Use math.random() for 0-1 float, math.random(n) for 1-n integer, math.random(m, n) for m-n integer. Always seed with math.randomseed(os.time()). {{< /faq >}}

What's Next

Now learn about booleans and logical operators in Lua.

Topic Description Link
Booleans Truthiness and logical ops {{< ref "16-booleans" >}}
Control Flow if, elseif, else {{< ref "17-control-flow" >}}

Built by the developers of DodaTech

Doda Browser, DodaZIP & Durga Antivirus Pro