Bennett Hermanoff
Bennett Hermanoff

Reputation: 11

How to change variables in applescript with if command

I have tried this forever, what am I doing wrong?

you get my variable repeatvar by

set repeatvar to the text returned of (display dialog "set repeatvar")

if repeatvar is greater than "1000" then
    set repeatvar to "1"
end if

when i enter any number it always just sets that number to 1, regardless of the number. What am I doing wrong?

Upvotes: 1

Views: 796

Answers (2)

vadian
vadian

Reputation: 285190

If you want to perform numeric comparison with strings – which behave different as integers – you have to tell AppleScript explicitly to consider numeric strings

set repeatvar to the text returned of (display dialog "set repeatvar" default answer "")
considering numeric strings
    if repeatvar is greater than "1000" then
        set repeatvar to "1"
    end if
end considering

Upvotes: 2

pbell
pbell

Reputation: 3105

The syntax of your first line is not correct. with this syntax, you will never get "text returned" valid value, but only valid "button returned". to have text returned, you must tell the script that you expect user to input a value. this is done by adding words "default answer"":

set repeatvar to the text returned of (display dialog "set repeatvar" default answer "")

The second issue with your text is that you want to compare the text entered with the string "1000". Comparing strings and numbers does not always give correct result. For instance strings are using alphabetical order and "9" is greater than "1000", because "9" > "1".

Script bellow will work :

set repeatvar to the text returned of (display dialog "set repeatvar" default answer "")
try
set myNumber to repeatvar as integer
on error
set myNumber to 0
end try
if myNumber is greater than 1000 then
set repeatvar to "1"
end if

Upvotes: 0

Related Questions