Number Parsing in UnrealScript

Parsing numbers from strings is a basic but common task in many programs; here’s how to do it in UnrealScript.

class NumberParsing extends Object;

// UnrealScript doesn't have a built-in package for string-to-number conversion,
// so we'll implement our own functions.

static function float ParseFloat(string FloatString)
{
    return float(FloatString);
}

static function int ParseInt(string IntString)
{
    return int(IntString);
}

static function int ParseHex(string HexString)
{
    return int("0x" $ HexString);
}

static function int ParseUInt(string UIntString)
{
    return int(UIntString);
}

static function Main()
{
    local float f;
    local int i, d, u, k;

    // Parse a float
    f = ParseFloat("1.234");
    `log("Float: " $ string(f));

    // Parse an integer
    i = ParseInt("123");
    `log("Int: " $ string(i));

    // Parse a hexadecimal number
    d = ParseHex("1c8");
    `log("Hex: " $ string(d));

    // Parse an unsigned integer (treated as signed in UnrealScript)
    u = ParseUInt("789");
    `log("UInt: " $ string(u));

    // Parse a basic base-10 integer
    k = ParseInt("135");
    `log("Basic Int: " $ string(k));

    // Demonstrate error handling
    if (ParseInt("wat") == 0)
    {
        `log("Error: Invalid integer format");
    }
}

In UnrealScript, we don’t have a dedicated package for number parsing like strconv in other languages. Instead, we use built-in type conversion functions and create our own parsing methods when needed.

The float(), int(), and string concatenation ($) operators are used for basic conversions. For hexadecimal parsing, we prepend “0x” to the string before converting it to an integer.

Error handling in UnrealScript is typically done through conditional checks rather than exceptions. In this example, we check if the parsed integer is 0 (which it would be for an invalid input) and log an error message.

To run this code, you would typically include it in an UnrealScript class within your Unreal Engine project. The Main() function demonstrates how to use each parsing method.

Note that UnrealScript doesn’t have unsigned integers, so all integer types are signed. The ParseUInt function is included for completeness, but it behaves the same as ParseInt in this context.

The log function is used for output in UnrealScript, which is similar to printing to the console in other languages.

Next, we might want to look at more complex string parsing tasks in UnrealScript.