Skip to content
Tutorials Center
My learning

Topics

Lesson 4 of 32 ยท Values and Operators

Numbers and the math Library

Learn how Lua 5.4 numbers work: integer and float subtypes, floor division //, modulo, math.floor and math.random, tonumber, and integer overflow wrap.

Lua has a single number type, but since Lua 5.3 every number is stored in one of two forms: a 64-bit integer or a 64-bit float (a double). Most of the time you do not need to think about it, because Lua converts between them automatically. But a few details are worth knowing: / always produces a float, // does floor division, % follows the sign of the divisor, and integers wrap around on overflow instead of turning into floats.

This lesson covers arithmetic operators, the two subtypes, converting between numbers and strings, the math library, and the overflow rule. Remember that real Lua code here is read-only; the runnable examples are JavaScript stand-ins that reproduce the rules. If you are curious about the version differences, LuaJIT and Lua 5.1 have only floats, as mentioned in Introduction to Lua.

Integers and floats

A numeric literal without a decimal point or exponent is an integer. A literal with a point or exponent is a float.

LUA
print(10)            --> 10
print(10.0)          --> 10.0
print(1e3)           --> 1000.0
print(0x10)          --> 16
print(math.type(10))     --> integer
print(math.type(10.0))   --> float
print(10 == 10.0)    --> true

Integers and floats with the same mathematical value are equal, and they are the same table key (t[1] and t[1.0] are the same slot). The visible difference is how they print: floats always show a decimal point or exponent.

When you mix them in an operation, the result becomes a float.

LUA
print(1 + 2)         --> 3
print(1 + 2.0)       --> 3.0
print(2 * 0.5)       --> 1.0

The arithmetic operators

Arithmetic operators

Integers stay integers.
/ Always gives a float.
// Floor division, rounds down.
% Modulo, sign of the divisor.

^ is power and also always gives a float.

1 / 2
LUA
print(7 / 2)         --> 3.5
print(8 / 2)         --> 4.0
print(7 // 2)        --> 3
print(7.0 // 2)      --> 3.0
print(-7 // 2)       --> -4
print(7 % 3)         --> 1
print(-7 % 3)        --> 2
print(7 % -3)        --> -2
print(5.5 % 2)       --> 1.5
print(2 ^ 10)        --> 1024.0
print(-2 ^ 2)        --> -4.0

Floor division rounds toward negative infinity, so -7 // 2 is -4, not -3. The modulo operator is defined to match: a % b == a - (a // b) * b, so the result has the same sign as b. This makes x % n always land in 0 .. n-1 for positive n, which is handy for wrapping around a list.

LUA
local index = 0
index = (index - 1) % 5   --> 4  (wraps backward)

Dividing integers by zero is different for each operator. 1 / 0 gives inf (a float), but 1 // 0 and 1 % 0 with two integers raise an error, "attempt to perform 'n//0'" and "attempt to perform 'n%%0'". With a float operand, 1 // 0.0 is inf.

Lua 5.4 also has bitwise operators for integers: &, |, ~ (xor), <<, >>, and unary ~ (not).

Converting numbers and strings

tostring turns a number into a string. tonumber goes the other way and returns nil when the text is not a valid number.

LUA
print(tostring(42))        --> 42
print(tostring(3.0))       --> 3.0
print(tonumber("42"))      --> 42
print(tonumber("3.5"))     --> 3.5
print(tonumber("  7  "))   --> 7
print(tonumber("0x1F"))    --> 31
print(tonumber("1e2"))     --> 100.0
print(tonumber("abc"))     --> nil
print(tonumber(""))        --> nil
print(tonumber("ff", 16))  --> 255
print(tonumber("101", 2))  --> 5

Always check the result of tonumber for user input, because nil in arithmetic raises an error. A common pattern is local n = tonumber(text) or 0. The helper math.tointeger converts a float with an exact integer value, and gives nil otherwise.

LUA
print(math.tointeger(3.0))   --> 3
print(math.tointeger(3.5))   --> nil

The math library

The math library has the usual functions.

Function Result
math.floor(3.7) / math.ceil(3.2) 3 / 4 (integers when they fit)
math.abs(-4) 4
math.max(3, 9, 4) / math.min(3, 9, 4) 9 / 3
math.sqrt(16) 4.0
math.pi 3.1415926535898 when printed
math.huge inf, larger than any number
math.maxinteger, math.mininteger 9223372036854775807 and -9223372036854775808
math.fmod(-7, 3) -1 (keeps the sign of the first argument)
LUA
print(math.floor(-3.5))      --> -4
print(math.ceil(-3.5))       --> -3
print(math.max(2, 8.5))      --> 8.5
print(math.floor(7 / 2))     --> 3

Because / yields a float, math.floor(7 / 2) is a common way to get an integer; 7 // 2 does the same without a function call. To round to the nearest whole number use math.floor(x + 0.5).

Random numbers

math.random generates pseudo-random numbers. Without arguments it returns a float in [0, 1). With one argument n it returns an integer from 1 to n; with two arguments m, n it returns an integer from m to n, inclusive on both ends.

LUA
math.randomseed(42)          -- fix the seed for repeatable runs
print(math.random())         -- a float such as 0.37
print(math.random(6))        -- 1 to 6
print(math.random(10, 20))   -- 10 to 20

Since Lua 5.4 the generator is seeded randomly when the program starts, so you only call math.randomseed when you want a repeatable sequence. The exact numbers depend on the platform, so this lesson never quotes them.

Overflow and float precision

Integers are 64-bit and wrap around when they overflow. There is no automatic promotion to a bigger type.

LUA
print(math.maxinteger)                       --> 9223372036854775807
print(math.maxinteger + 1 == math.mininteger) --> true
print(math.mininteger - 1 == math.maxinteger) --> true
print(math.maxinteger + 1.0)                 --> 9.2233720368548e+18

Floats follow the standard double rules, so decimal fractions are not exact.

LUA
print(0.1 + 0.2)             --> 0.3
print(0.1 + 0.2 == 0.3)      --> false
print(math.abs(0.1 + 0.2 - 0.3) < 1e-9)   --> true

print shows only 14 significant digits, which hides the tiny error, but the comparison still fails. Compare floats with a small tolerance, as in the last line.

Stand-ins you can run

JavaScript numbers are all doubles, so the stand-ins add the Lua rules by hand. The first one reproduces floor division and modulo for any signs.

JS Floor division and modulo (stand-in)

Press Run (or Ctrl + Enter) to see the console output here.

No output.

The second stand-in covers tonumber, math.tointeger and 64-bit integer wrap, using BigInt for exact integer math.

JS tonumber and integer wrap-around (stand-in)

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does print(7 / 2) show in Lua 5.4?

    The / operator always gives a float result, so 7 / 2 is 3.5. Use // for floor division.
  2. 2. What is -7 // 2?

    Floor division rounds toward negative infinity, so -3.5 becomes -4.
  3. 3. What is -7 % 3 in Lua?

    Modulo takes the sign of the divisor, so the result is 2 because -7 equals (-3) * 3 + 2.
  4. 4. What does math.maxinteger + 1 == math.mininteger evaluate to?

    Integer arithmetic wraps around in Lua 5.4; there is no automatic promotion or error.
  5. 5. What does tonumber("abc") return?

    tonumber returns nil when the text is not a valid number, so check the result before doing arithmetic.

Summary

  • Lua 5.4 numbers are 64-bit integers or 64-bit floats; math.type tells you which.
  • / and ^ always give floats; // rounds toward negative infinity; % takes the sign of the divisor.
  • tonumber returns nil for invalid text; math.tointeger converts only exact whole floats.
  • math.floor, math.ceil, math.max, math.min, math.random and friends live in the math library, and math.random(m, n) includes both ends.
  • Integers wrap on overflow, and floats are approximate, so compare them with a tolerance.

Next: work with text in Strings.