Skip to content

Num

Source: shiva-fw/libs/num/init.lua

Number utility library.

Availability

Num is a global in every shiva module (loaded by sh_init.lua). No import required.

Clamping and Rounding

Num.clamp(n, min, max)

Clamp n between min and max.

lua
Num.clamp(150, 0, 100)  -- 100

Num.round(n, decimals?)

Round to decimal places (default: 0).

lua
Num.round(3.14159, 2)  -- 3.14

Formatting

Num.format(n)

Format with comma thousands separators.

lua
Num.format(1000000)  -- '1,000,000'

Num.currency(n, symbol?)

Format as a currency string. Default symbol: '$'.

lua
Num.currency(1500)          -- '$1,500.00'
Num.currency(1500, '€')     -- '€1,500.00'
Num.currency(-500)          -- '-$500.00'

Num.percent(n, decimals?)

Format a value between 0 and 1 as a percentage string.

lua
Num.percent(0.75)      -- '75%'
Num.percent(0.5, 1)    -- '50.0%'

Num.compact(n, decimals?)

Compact notation (K/M/B). Default decimals: 1.

lua
Num.compact(1500)       -- '1.5K'
Num.compact(2000000)    -- '2.0M'

Interpolation and Mapping

Num.lerp(a, b, t)

Linear interpolation. t is clamped to [0, 1].

lua
Num.lerp(0, 100, 0.5)  -- 50

Num.inverseLerp(a, b, value)

Find t for a value between a and b.

lua
Num.inverseLerp(0, 100, 75)  -- 0.75

Num.map(value, fromMin, fromMax, toMin, toMax)

Map a value from one range to another.

lua
Num.map(50, 0, 100, 0, 255)  -- 127.5

Comparison

Num.between(n, min, max)

Return true if n is between min and max (inclusive).

lua
Num.between(50, 0, 100)  -- true

Num.percentOf(part, total)

Calculate percentage of a total (0–100).

lua
Num.percentOf(25, 200)  -- 12.5

Random

Num.random(min, max)

Random integer (inclusive).

lua
Num.random(1, 100)

Num.randomFloat(min, max)

Random float.

lua
Num.randomFloat(0.0, 1.0)

Unit Conversions

lua
Num.metersToFeet(meters)  -- meters × 3.28084
Num.kmhToMph(kmh)         -- kmh × 0.621371
Num.mphToKmh(mph)         -- mph × 1.60934

Released under the MIT License.