AppleScript 入门

AppleScript 入门_第1张图片
脚本编辑器

前言

AS 是能够帮你在 mac 上实现自动化的有效工具,他通过类英语的语法,以及简单的编程功能,帮助你摆脱机械化的劳动。

AppleScript 包括如下三部分:

  • AppleScript 语言
  • AppleScript 脚本文件
  • AppleScript 脚本解释器

工具

在 mac 中自带 AutomatorAppleScript Editor 均可以编写脚本。其中 Automator 是可视化工具,但功能更基础(似乎连循环都没有)。

一些 AppleScript 的脚本样例

Hello World
tell current application
    display dialog "Hello World."
end tell
Hello *
tell current application
    set str to "xp"
    display dialog "Hello " & str
end tell
Empty the trash
tell application "Finder"
    empty the trash
    beep
end tell
Say Hello
say "How are you?" using "Zarvox"
say "Fine, and you?" using "Victoria"
say "Me, too." using "Zarvox"
beep

语法简介

AS 是面向对象的脚本语言,有三个重要的OO术语:对象(Object)、属性(Property)、命令(Command)

命令又称方法(Method),这些都是苹果官方《AppleScript Language Guide》的说法。

标识符(Identifier)

AS 采用 Unicode 编码,不区分大小写。

标识符必须以英文字母开头,可使用英文字母、数字和下划线(_)。

额外规则:若以|开头并结尾,可使用任意 Unicode 字符作为标识符,但注意标识符本身不含有|不推荐使用这种写法。

综上所述,合法的标识符如:abc, a0, |a&b|, |中文|

关键字(Keyword)

语言保留使用的标识符称为关键字,请注意 AS 中存在由多个词组成的关键字

变量
set var to value

数据类型

  • Boolean: true, false
  • Number: 1, 1.0, -1
    整型和实数型都属于数字型。
  • Text: "string"
  • String
    这是旧版 AS2.0 的数据类型,同 Text,用于向下兼容。
  • Date: date "2009-8-30 12:31:34"
    此格式由 系统偏好设置-语言与文本 决定
  • Constant: yes, no, ask
  • List: { 1, 2, "str", { 4, 5 } }
  • Record: { key1: value, key2: value }
    通过 key of {key: value} 访问其值

通过 class of 关键字来确定数据类型:

-- 这是注释
set str to "string"
class of str -- 返回 "text"

使用 as 关键字强制类型转换:

"1.99" as real    -- 1.99 (real)
"1.99" as integer -- 2 (integer) 精度丢失
"1" as real       -- 1.0  (real)

"text" as list    -- { "text" }

{ a: 1, b: 2 } as list -- { 1, 2 } 精度丢失

不是所有的数据都能够强制类型转换,不要纠结于此,做有意义的事。

分支语句
if condition then
    do sth.
end if
循环语句
repeat with i from 1 to 100
    do sth.
end repeat

更多

更多语法请参阅 AppleScript Editor 中提供的 字典。或者阅读 AppleScript 简明基础教程。

你可能感兴趣的:(AppleScript 入门)