How do I check if text can be converted to a number in AppleScript?

醉酒当歌 提交于 2020-01-03 04:00:08

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!