Lua Math Functions
Lua math functions are ready-made tools in the math library that round, compare, and calculate numbers. This lesson covers the tools used most often in small programs.
Round down and up
math.floor rounds down and math.ceil rounds up. Printing both results shows the pair side by side.
print(math.floor(3.7), math.ceil(3.2))Size, largest, and smallest
math.abs drops a minus sign from a number. math.max and math.min pick the ends of a small set of values.
print(math.abs(-5), math.abs(5))
print(math.max(2, 9, 4), math.min(2, 9, 4))Square root and pi
math.sqrt gives the square root as a float. string.format shows pi with two decimal digits.
print(math.sqrt(16))
print(string.format("%.2f", math.pi))Example
local width = 13
local tilesAcross = width // 2
local area = math.pi * 3 * 3
print("Tiles:", tilesAcross)
print(string.format("Area: %.2f", area))
print("Whole area:", math.ceil(area))Key points
- Math library: a built-in group of number tools whose names start with math followed by a dot.
- math.floor: a tool that rounds a number down to the nearest whole number.
- math.ceil: a tool that rounds a number up to the nearest whole number.
- math.abs: a tool that returns the size of a number without its minus sign.
- math.max and math.min: tools that return the largest and smallest values in a list.
- math.sqrt and math.pi: tools that give the square root of a number and the value of pi.
In this example, floor division works out that six whole tiles of width 2 fit across a width of 13. The circle area uses math.pi times the radius 3 times itself, printed with two decimal digits. math.ceil then rounds that area up to 29 whole units.
Note
math.sqrt returns a float, so the square root of 16 prints as 4.0.
Try it Yourself
Edit the code, then press Run.
Running is simulated
Exercise
What do math.floor(4.9) and math.ceil(4.9) return?