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:
We define custom functions
ParseFloat
,ParseInt
, andParseUint
to mimic the functionality of Go’sstrconv
package. These functions use AngelScript’s built-instring_to_float
,string_to_int64
, andstring_to_uint64
functions.The
ParseInt
andParseUint
functions accept an optionalbase
parameter, defaulting to 10 for decimal numbers.For parsing hexadecimal numbers, we explicitly pass 16 as the base to
ParseInt
.AngelScript doesn’t have a direct equivalent to Go’s
Atoi
function, so we useParseInt
and cast the result toint
.Error handling in AngelScript is typically done with exceptions, so we use a try-catch block to handle parsing errors.
We use AngelScript’s
print
function instead of Go’sfmt.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.