Skip to main content

string.tointeger()

Converts a string of numeric characters to an integer value

Availability

Device + Agent

Returns

Integer — the value of the numeric string

Description

This method returns the integer value represented by the target string, which should contain only numeric characters, and the minus and plus symbols to indicate negative and positive values, respectively. Starting a string with non-numerical characters can cause Squirrel to post a ‘cannot convert the string’ error.

If you prefix a string with one or more numeric characters, Squirrel will convert those to an integer and ignore the remainder of the string:

server.log("2timesfour".tointeger());
// Logs '2'

Squirrel will convert hexadecimal strings prefixed with 0x into integer values:

server.log("0xFF".tointeger());
// Logs '255'

If the hexadecimal string contains more than ten characters (including the 0x) it will return -1, even if the lowest four bytes represent a positive value:

server.log("0x01FFFFFFFF".tointeger());
// Logs '-1'

server.log("0x10FFFFFFF".tointeger());
// Logs '-1'

To trap cases where the string is not numeric, use Squirrel’s try... catch structure:

local aString = "Zap!";
local value = -1;

try {
    local = aString.tointeger();
catch (err) {
    server.error("Integer conversion attempted on non-numeric string; defaulting to 0");
    local = 0;
}

server.log(local);
// Logs '0'

Example Code