问题
I'm trying to write a simple AppleScript to do some text manipulation on the contents of the clipboard. The following code works only if the text in the clipboard can be converted to a number:
set CB to the clipboard
set bugNum to CB as number
But if the text in the clipboard is not a number I get an AppleScript error: "Can’t make "foo" into type number."
How do I write an if condition that I can use to check if CB (of class text) can be converted to a number (and put the "set bugNum to CB as number" inside that)? Or can I "catch" the error somehow?
回答1:
Did you already read working with errors in the Applescript guide?
Sample code:
set CB to the clipboard
try
set bugNum to CB as number
on error errStr number errNum
set bugNum to -1
end try
display dialog "Number from the clipboard: " & bugNum
I skipped the code the first time round since I figured the guide was pretty clear, and far more useful than anything I could write here :)
来源:https://stackoverflow.com/questions/918493/how-do-i-check-if-text-can-be-converted-to-a-number-in-applescript