Skip to content

Math Shared ​

Math is a module to extend Lua's standard mathematical library with additional utility functions for common calculations and operations needed in game development. It provides helpful functions for interpolation, rounding with precision, and other mathematical operations that aren't available in the base Lua math library.

Math Functions ​

math.clamp() ​

Clamps a number between a minimum and maximum value.

Syntax ​

lua
math.clamp(x, min, max)

Parameters ​

x : number

The number to clamp

min : number

The minimum value

max : number

The maximum value

Return Value ​

Type : number

The clamped number


math.fromHex() ​

Converts a hexadecimal string to an integer.

Syntax ​

lua
math.fromHex(hex)

Parameters ​

hex : string

The hexadecimal string to convert, with or without "0x" prefix

Return Value ​

Type : integer

The integer representation


math.lerp() ​

Performs linear interpolation between two values.

Syntax ​

lua
math.lerp(a, b, t)

Parameters ​

a : number

The starting value

b : number

The ending value

t : number

The interpolation factor, usually between 0 and 1

Return Value ​

Type : number

The interpolated value between a and b

Example ​

lua
local startValue = 0
local endValue = 100
local factor = 0.5 -- 50% between start and end

local result = math.lerp(startValue, endValue, factor)
print(result) -- Output: 50

math.round() ​

Rounds a number to the specified decimal precision.

Syntax ​

lua
math.round(number, precision)

Parameters ​

number : number

The number to round

precision : number Optional

The number of decimal places to round to
default:0

Return Value ​

Type : number

The rounded number

Example ​

lua
-- Round to nearest whole number (no precision parameter)
local value1 = 3.7
local rounded1 = math.round(value1)
print(rounded1) -- Output: 4

-- Round to specific decimal places
local value2 = 3.14159
local rounded2Decimal = math.round(value2, 2)
print(rounded2Decimal) -- Output: 3.14

local price = 19.9567
local formattedPrice = math.round(price, 2)
print("$" .. formattedPrice) -- Output: $19.95

math.toHex() ​

Converts a number to hexadecimal string representation.

Syntax ​

lua
math.toHex(n, prefix)

Parameters ​

n : integer

The integer to convert

prefix : boolean Optional

Add "0x" prefix, default: false

Return Value ​

Type : string

The hexadecimal string representation


math.toSigned() ​

Syntax ​

lua
math.toSigned(n)

Last updated: