math module

Extends the Lua 5.2 math library, adding more capabilities and functions.

Usage

local math = require("__flib__.math")

Functions

round(num) Round a number to the nearest integer.
round_to(num, num_decimals) Round a number to the nearest N decimal places.
ceil_to(num, num_decimals) Ceil a number to N decimal places.
floor_to(num, num_decimals) Floor a number to N decimal places.
mean(set) Calculate the mean (average) of a set of numbers.
clamp(x, min, max) Clamp a number between minimum and maximum values.
lerp(num1, num2, amount) Linerarly interpolate between num1 and num2 by amount.

Constants

deg_to_rad Multiply by degrees to convert to radians.
rad_to_deg Multiply by radians to convert to degrees.
max_int8 127
min_int8 -128
max_uint8 255
max_int16 32,767
min_int16 -32,768
max_uint16 65,535
max_int 2,147,483,647
min_int -2,147,483,648
max_uint 4,294,967,296
max_int53 9,007,199,254,740,991
min_int53 -9,007,199,254,740,992

Functions

# round(num)

Round a number to the nearest integer.

This function is measurably faster than math.round_to and should be used in place of it where applicable.

From lua-users.org.

Parameters: Returns:
# round_to(num, num_decimals)

Round a number to the nearest N decimal places.

Use math.round if no decimals are needed. From lua-users.org.

Parameters: Returns:
# ceil_to(num, num_decimals)

Ceil a number to N decimal places.

Use math.ceil directly if no decimals are needed.

Parameters: Returns:
# floor_to(num, num_decimals)

Floor a number to N decimal places.

Use math.floor directly if no decimals are needed.

Parameters: Returns:
# mean(set)

Calculate the mean (average) of a set of numbers.

Parameters:
  • set : (array) An array of numbers to find the average of.
Returns:
  • (number) The mean of the set.
# clamp(x, min, max)

Clamp a number between minimum and maximum values.

Parameters: Returns:
# lerp(num1, num2, amount)

Linerarly interpolate between num1 and num2 by amount.

The parameter amount is clamped between 0 and 1.

When amount = 0 returns num1.

When amount = 1 returns num2.

When amount = 0.5 returns the midpoint of num1 and num2.

Parameters:
  • num1 : (number) The start value.
  • num2 : (number) The end value.
  • amount : (number) The interpolation value between the two numbers.
Returns:
  • (number) The interpolated result between the two numbers.

Constants

# deg_to_rad

Multiply by degrees to convert to radians.

Usage:
local deg = 1
local rad = deg x flib_math.deg_to_rad -- 0.0174533
# rad_to_deg

Multiply by radians to convert to degrees.

Usage:
local rad = 1
local deg = rad x flib_math.rad_to_deg -- 57.2958
# max_int8

127

# min_int8

-128

# max_uint8

255

# max_int16

32,767

# min_int16

-32,768

# max_uint16

65,535

# max_int

2,147,483,647

# min_int

-2,147,483,648

# max_uint

4,294,967,296

# max_int53

9,007,199,254,740,991

# min_int53

-9,007,199,254,740,992