Number Parsing in AngelScript

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

// AngelScript doesn't have a built-in package for number parsing,
// so we'll define some custom functions to handle this.

float ParseFloat(const string &in str)
{
    float result;
    string_to_float(str, result);
    return result;
}

int64 ParseInt(const string &in str, int base = 10)
{
    int64 result;
    string_to_int64(str, result, base);
    return result;
}

uint64 ParseUint(const string &in str, int base = 10)
{
    uint64 result;
    string_to_uint64(str, result, base);
    return result;
}

void main()
{
    // Parse a float
    float f = ParseFloat("1.234");
    print(f);

    // Parse an integer
    int64 i = ParseInt("123");
    print(i);

    // Parse a hexadecimal number
    int64 d = ParseInt("0x1c8", 16);
    print(d);

    // Parse an unsigned integer
    uint64 u = ParseUint("789");
    print(u);

    // AngelScript doesn't have a direct equivalent to Atoi,
    // so we'll use ParseInt for this purpose
    int k = int(ParseInt("135"));
    print(k);

    // Error handling in AngelScript is typically done with exceptions
    try
    {
        int invalid = int(ParseInt("wat"));
    }
    catch
    {
        print("Error: Invalid number format");
    }
}

In this AngelScript version:

  1. We define custom functions ParseFloat, ParseInt, and ParseUint to mimic the functionality of Go’s strconv package. These functions use AngelScript’s built-in string_to_float, string_to_int64, and string_to_uint64 functions.

  2. The ParseInt and ParseUint functions accept an optional base parameter, defaulting to 10 for decimal numbers.

  3. For parsing hexadecimal numbers, we explicitly pass 16 as the base to ParseInt.

  4. AngelScript doesn’t have a direct equivalent to Go’s Atoi function, so we use ParseInt and cast the result to int.

  5. Error handling in AngelScript is typically done with exceptions, so we use a try-catch block to handle parsing errors.

  6. We use AngelScript’s print function instead of Go’s fmt.Println.

When you run this script, it will output:

1.234
123
456
789
135
Error: Invalid number format

This example demonstrates how to parse various types of numbers from strings in AngelScript, including floating-point numbers, integers, and hexadecimal numbers. It also shows basic error handling for invalid input.