Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does AppleScript have an equivalent for the conditional (ternary) operator?

Being familiar with programming, I am missing the ability to assign variables with ternary operators (i.e "set the variable to x if something is true, otherwise set it to y"). I'm thinking of something like:

set my_string to (if a is 0 return "" else return " - substring")

This of course doesn't work, and I haven't found anything similar yet. Would there be another way to achieve this with applescript?

like image 829
uɥƃnɐʌuop Avatar asked Dec 25 '12 21:12

uɥƃnɐʌuop


1 Answers

Looks like AppleScript doesn't support the conditional operator but you can use list with two elements for that purpose. Of course, it's not very elegant in general:

set my_string to item (((a is 0) as integer) + 1) of {"", " - substring"}

And there is another way: you can use shell script

set b to (do shell script "test " & a & " -eq 0 && echo 'is 0' || echo 'is not 0'")

How could I forget this? :)

And in your case it will be even more simple (because an empty string will be returned if there is no echo at all).

set b to (do shell script "test " & a & " -eq 0 || echo '- substring'")
like image 159
cody Avatar answered Sep 30 '22 20:09

cody