user3451226 user3451226 - 4 months ago 11
AppleScript Question

"set foo to text returned of" for numbers?

I know you can do

set foo to text returned of (display dialog "Dialog" default answer "default")
.
I've tried everything from
set foo to number returned of
or
set foo to integer returned of
but I can't seem to find the keyword for returning a number. Any help?

Answer

You need to get the text returned, and then coerce it into an integer:

set foo to (text returned of (display dialog "Enter a number" default answer "42")) as integer

or, broken up more to illustrate is:

display dialog "Enter a number" default answer "42"
set foo to text returned of the result
set foo to foo as integer

I would separate it out so you can wrap a try block around the coercion in the event that it's not a number.

set foo to text returned of (display dialog "Enter a number" default answer "42")
try
    set foo to foo as integer
on error err
    set foo to 0
end

And, here would be one way of repeatedly asking until they supply a valid number:

set msg to "Enter a number"
repeat
    set foo to text returned of (display dialog msg default answer "42")
    try
        set foo to foo as integer
        exit repeat
    on error err
        set msg to "That's not a valid number. Please enter a number."
    end try
end repeat
return foo