Skip to main content

std:math

The std:math module provides common mathematical functions for Lua. It includes trigonometry with unit specification, exponentiation, logarithms, square roots, and factorials.


Functions

math.cos(x: number, unit: 'r'|'g'): number

Returns the cosine of x.

  • Parameters:

    • x (number): the angle.
    • unit (string): 'r' for radians, 'g' for degrees.
  • Returns:

    • (number) the cosine of x.

Example:

local math = require("std:math")
print(math.cos(math.pi / 3, 'r')) -- 0.5
print(math.cos(60, 'g')) -- 0.5

math.sin(x: number, unit: 'r'|'g'): number

Returns the sine of x.

  • Parameters:

    • x (number): the angle.
    • unit (string): 'r' for radians, 'g' for degrees.
  • Returns:

    • (number) the sine of x.

Example:

local math = require("std:math")
print(math.sin(math.pi / 2, 'r')) -- 1
print(math.sin(90, 'g')) -- 1

math.tan(x: number, unit: 'r'|'g'): number

Returns the tangent of x.

  • Parameters:

    • x (number): the angle.
    • unit (string): 'r' for radians, 'g' for degrees.
  • Returns:

    • (number) the tangent of x.

Example:

local math = require("std:math")
print(math.tan(math.pi / 4, 'r')) -- 1
print(math.tan(45, 'g')) -- 1

math.sqrt(x: number): number

Returns the square root of x.

  • Parameters:

    • x (number): value to compute the square root of.
  • Returns:

    • (number) the square root of x.

Example:

local math = require("std:math")
print(math.sqrt(16)) -- 4

math.pow(x: number, y: number): number

Returns x raised to the power of y.

  • Parameters:

    • x (number): base.
    • y (number): exponent.
  • Returns:

    • (number) x^y.

Example:

local math = require("std:math")
print(math.pow(2, 3)) -- 8

math.fact(n: integer): integer

Returns the factorial of n.

  • Parameters:

    • n (integer): non-negative integer.
  • Returns:

    • (integer) n!.

Example:

local math = require("std:math")
print(math.fact(5)) -- 120

math.log(x: number): number

Returns the natural logarithm (base e) of x.

  • Parameters:

    • x (number): value to compute the logarithm of.
  • Returns:

    • (number) the natural logarithm of x.

Example:

local math = require("std:math")
print(math.log(1)) -- 0

Constants

ConstantValueDescription
pi3.14159265358979323846Ratio of circle circumference to diameter
e2.71828182845904523536Euler's number, base of natural logarithms
tau6.283185307179586476922π, full circle in radians
phi1.61803398874989484820Golden ratio
G6.67430×10⁻¹¹Gravitational constant, m³·kg⁻¹·s⁻²