Home > Enterprise >  How can I stop Applescript from comparing strings to numbers?
How can I stop Applescript from comparing strings to numbers?

Time:10-17

So I just found out that strings can be compared to each other in Applescript like this:

"hello world" > "abc"

Returns:

true

However, you can also compare strings to numbers. The string will, however always be greater:

"a" = 10 ^ 308 -- Close to infinity

Returns:

false

Is there a way to only compare numbers without using try- and on error-statements?

CodePudding user response:

An easy way around this is to check for the class of the variable or string you are passing:

set x to "This is my innocent string"
if x > 0 and class of x ≠ string then --do stuff here.

CodePudding user response:

The meaning of your exercises is incomprehensible. It is not clear what is the use? AppleScript is written exactly the way the developers wanted it to be. For example, they thought: why not compare a string to a number. You can't (and it's good that you can't) change the behavior of AppleScript's logical operations. But you can write your "smart equivalents" to them. And use them.

on isNumbersEqual(x, y)
    if (class of x is not in {real, integer}) or (class of y is not in {real, integer}) then
        error "SOME OPERAND(s) IS NOT NUMBER."
    end if
    x = y
end isNumbersEqual

-- isNumbersEqual("1", 10 ^ 308) --> ERROR!!
isNumbersEqual(1, 10 ^ 308) --> false

Note: Unlike other programming languages, AppleScript does not throw an error when comparing strings to numbers. Instead, it implicitly coerces the number to a string to perform a legitimate comparison. You can check my statement:

("1" > 10 ^ 308) is ("1" > (10 ^ 308 as string)) --> true
  • Related