CRPL: comparing strings and numbers

Started by eduran, December 03, 2013, 06:30:49 AM

Previous topic - Next topic

eduran

"string" ->string
0 ->zero
1 ->one
Trace(<-string eq(<-one)) # returns 0/FALSE
Trace(<-string eq(<-zero)) # returns 1/TRUE

"1" ->OneAsString
Trace(<-OneAsString eq(<-one)) # returns 1/TRUE
Trace(<-OneAsString eq(<-zero)) # returns 0/FALSE


Compare any string to 0 and you get TRUE as a result. Except when you compare a string that represents a number. Intended behavior or a bug?

knucracker

What happens is that when you try to do a numeric comparison where one argument is a string and the other is an int, that string gets coerced into an int.  If the string is something like "42" that coerces into 42.  If it is "abc" that coerces into 0.

The 'eq' (and other comparators) look at both arguments and their intrinsic types.  The rules are:
1: If either argument is a floating point number, then treat both arguments as floating point numbers, coercing the other argument if necessary.
2: If both arguments are strings, then do string comparisons.  So, EQ would compare strings, for instance.
3: If neither 1 nor 2 above is true, then treat each argument as an int, coercing the arguments if necessary.


Grauniad

I added this to the wiki page and referenced it on all other comparators.
A goodnight to all and to all a good night - Goodnight Moon