Math Library

For more than + - * /, Lua has the math library. Its functions are called with a dot, like math.floor(x). Numbers are not strings, so there is no colon call here.

Rounding down and up

print(math.floor(3.7))
print(math.ceil(3.2))
print(17 / 2)
print(math.floor(17 / 2))

Output:

3
4
8.5
8

math.floor rounds down to a whole number, and math.ceil rounds up. They always go in that direction, so the floor of 3.7 is 3, not 4.

Remember that / always gives a decimal number, even when you divide whole numbers. math.floor(17 / 2) is a common way to get a whole number back. The result prints as 8, not 8.0.

Smallest, largest and more

print(math.min(4, 9, 2))
print(math.max(4, 9, 2))
print(math.abs(-8))
print(math.sqrt(16))
print(math.pi)

Output:

2
9
8
4.0
3.1415926535898
  • math.min and math.max return the smallest and the largest of their arguments. You can pass two numbers or many.
  • math.abs removes the minus sign.
  • math.sqrt is the square root. Like /, it always gives a decimal number, so you see 4.0.
  • math.pi is not a function, just a value.

Random numbers

math.random(6) returns a random whole number from 1 to 6, like rolling a die:

print(math.random(6))
print(math.random(6))

Run it a few times and you get different numbers each time. That is the point of random numbers, and it is also why the exercises in this course don't use them: their output must be the same on every run so it can be checked.

In the exercise, read two numbers and use math.min, math.max and math.floor to print the smaller one, the larger one and their average rounded down.