条件语句
if - else if - else语句块
AppleScript中的条件语句形式如下:
if 条件 then
...
else if 条件 then
...
else
...
end if
使用例如:
-- Numbers compare = <= >= /=
set num1 to 10
set num2 to 20
-- if num1 is num2 then
if num1 = num2 then
display dialog "num1 == num2"
else
display dialog "num1 != num2"
end if
if num1 ≥ num2 then
1
else if num1 ≤ num2 then
2
else
3
end if
最简单的形式是:
if 条件 then ...
注意上面的语句必须在同一行内完成。不需要也不能有end if出现。
使用例如:
if true then set x to 1
-- error
-- if false then set y to 0 end if
比较number
关于number之间的比较符号:= , <= , >= , /=(注意不是!=)分别代表等于,小于或等于,大于或等于,不等于。
经过编译后比较符号会变成以下形式:
原书中对各种比较符号和对应的逻辑关键词列举如下:
比较string
string之间的比较使用逻辑关键词,这里就直接贴出原书的总结吧:
对于逻辑运算符用and,or,not表示与,或,非。
循环语句
循环语句有几种形式,类似于OC中的for循环,while循环,for in循环等。
repeat X times
类似于for循环的形式如下:
repeat 重复的次数 times
...
end repeat
使用例如:
repeat 2 times
say "repeat"
end repeat
重复次数可以是一个数字变量,例如:
set repeatTimes to 10
repeat repeatTimes times
say "repeat"
end repeat
repeat from to by
另外一种类似for循环的形式为:
repeat with 计数变量 from 初始值 to 目标值 by 递增数
...
end repeat
by递增数部分可以缺省,如果缺省了那么每次计数变量加1。
使用举例:
repeat with counter from 1 to 3
display dialog counter
end repeat
repeat with counter from 0 to 10 by 2
display dialog counter
end repeat
repeat while
类似于while循环的形式1:
repeat while 条件
...
end repeat
set counter to 0
repeat while counter ≠ 10
display dialog counter as string
set counter to counter + 2
end repeat
repeat until
形式2:
repeat until 条件
...
end repeat
set counter to 0
repeat until counter = 10
display dialog counter as string
set counter to counter + 2
end repeat
repeat in
当然你可能猜到了,还有类似于for in循环的语句,可以用来遍历列表。形式如下:
repeat with 单个元素 in 集合
...
end repeat
使用例如:
set aList to {1, 2, 3}
repeat with anItem in aList
display dialog anItem as string
end repeat
有了条件语句和循环语句,可以按我们的逻辑思维去写代码了。
更多详细内容请参考《AppleScript for Absolute Starters》一书(中文名为《苹果脚本跟我学》)。