math.tointeger

Shared

Converts a number to an integer if it has no fractional part, otherwise returns nil


Syntax

local result = math.tointeger(
    value
)

Parameters

TypeNameDescription
numbervalueNumber to attempt converting to an integer

Returns

TypeNameDescription
int | nilresultConverted result:
int — exact integer representation of value
nil — value has a fractional part or is not a number

Examples

Convert a whole float to integer
local result = math.tointeger(5.0)

engine.print("info", result) -- 5
Returns nil for a float with a fraction
local result = math.tointeger(5.5)

engine.print("info", result) -- nil
Convert a negative whole float
local result = math.tointeger(-3.0)

engine.print("info", result) -- -3
Returns nil for a non-number
local result = math.tointeger("hello")

engine.print("info", result) -- nil
Safely convert a computation result to integer
local val = 2 ^ 10
local int_val = math.tointeger(val)

if int_val then
    engine.print("info", "Integer:", int_val) -- Integer: 1024
else
    engine.print("info", "Not an exact integer")
end
Validate that a computed index is a whole number
local index = 9 / 3
local int_index = math.tointeger(index)

if int_index then
    engine.print("info", "Valid index:", int_index) -- Valid index: 3
end

On this page