Lua Math Library

Lua’s math library provides a powerful suite of mathematical functions that can be used in scripting tasks ranging from simple arithmetic to advanced trigonometry and random number generation. Whether you’re creating games, simulations, or automation scripts, understanding this library is essential.

Below is a breakdown of all the key functions and constants provided by Lua’s math module.


Trigonometric Functions

These functions expect and return radians (use math.rad and math.deg to convert):

Function Description
math.sin(x) Returns the sine of x.
math.cos(x) Returns the cosine of x.
math.tan(x) Returns the tangent of x.
math.asin(x) Returns the arcsine of x.
math.acos(x) Returns the arccosine of x.
math.atan(x) Returns the arctangent of x.
math.atan2(y, x) Returns atan(y/x) taking signs into account.

Conversion Utilities

Function Description
math.rad(deg) Converts degrees to radians.
math.deg(rad) Converts radians to degrees.

Hyperbolic Functions (in LuaJIT or extended environments like Cheat Engine)

Function Description
math.sinh(x) Hyperbolic sine.
math.cosh(x) Hyperbolic cosine.
math.tanh(x) Hyperbolic tangent.

Exponential & Logarithmic Functions

Function Description
math.exp(x) Exponential e^x.
math.log(x) Natural logarithm (base e).
math.log10(x) Logarithm base 10.
math.pow(x, y) Raises x to the power of y.
math.sqrt(x) Square root of x.

Random Number Generation

Function Description
math.random() Returns a float in [0, 1).
math.random(n) Integer from 1 to n.
math.random(m, n) Integer from m to n.
math.randomseed(seed) Seeds the random number generator (important!).

:warning: Always call math.randomseed(os.time()) (or a custom seed) to ensure random results across runs.

Arithmetic Helpers

Function Description
math.abs(x) Absolute value.
math.floor(x) Largest integer ≤ x.
math.ceil(x) Smallest integer ≥ x.
math.fmod(x, y) Remainder of x / y with sign of x.
math.modf(x) Returns integer and fractional parts.
math.tointeger(x) Converts x to an integer or returns nil.

Bitwise-Like Helpers & Floating-Point Tools

Function Description
math.frexp(x) Breaks x into mantissa and exponent.
math.ldexp(m, e) Computes m * 2^e. Useful with frexp.
math.ult(x, y) True if x < y unsigned (Lua 5.3+).

Extrema and Constants

Function/Constant Description
math.min(a, b, ...) Returns the smallest value.
math.max(a, b, ...) Returns the largest value.
math.pi π ≈ 3.14159
math.huge A special value representing infinity.
math.maxinteger Largest representable integer (Lua 5.3+).
math.mininteger Smallest representable integer (Lua 5.3+).

Tips

  • Radians vs Degrees: Always check if your trigonometric functions expect radians.
  • Random Numbers: Don’t forget to use randomseed() to avoid deterministic outputs.
  • Performance: math functions are optimized and often faster than equivalents in Lua written by hand.