问题描述
AppleScript 文档建议使用以下代码来有效地构建列表:
AppleScript documentation suggests the following code to efficiently build a list:
set bigList to {}
set bigListRef to a reference to bigList
set numItems to 100000
set t to (time of (current date)) --Start timing operations
repeat with n from 1 to numItems
copy n to the end of bigListRef
end
set total to (time of (current date)) - t --End timing
注意显式引用的使用.这在脚本的顶层或显式运行处理程序中工作正常,但如果您在另一个处理程序中逐字运行相同的代码,如下所示:
Note the use of an explicit reference. This works fine at the top level of a script or within an explicit run handler, but if you run the same exact code verbatim within another handler like so:
on buildList()
set bigList to {}
set bigListRef to a reference to bigList
set numItems to 100000
set t to (time of (current date)) --Start timing operations
repeat with n from 1 to numItems
copy n to the end of bigListRef
end
set total to (time of (current date)) - t --End timing
end buildList
buildList()
它中断了,产生一条错误消息,说无法将 bigList 设为类型引用."为什么这会中断,在 run() 之外的处理程序中有效构建列表的正确方法是什么?
it breaks, yielding an error message saying, "Can't make bigList into type reference." Why does this break, and what is the correct way to efficiently build a list within a handler other than run()?
推荐答案
在 buildList() 的第一行添加global bigList"修复了编译器错误.似乎在运行处理程序中,默认情况下变量是裸露的,而引用"运算符很有用.然而,在其他上下文中,变量本质上已经是间接引用,创建另一个引用层会破坏一些东西.在这些上下文中声明全局变量会剥离间接引用并允许引用到"操作符起作用,但这是不必要的.只需使用默认的间接引用.
Adding "global bigList" to the first line of buildList() fixes the compiler error. It seems that within the run handler, variables are naked by default, and the "a reference to" operator is useful. However, in other contexts, variables are already essentially indirect references, and creating another reference layer breaks stuff. Declaring a global variable in these contexts strips the indirect reference and allows the "a reference to" operator to work, but this is unnecessary. Just use the default indirect reference.
如果这不清楚,那是因为我不完全了解其中的机制.如果您对这里发生的事情有更好的了解,请在下方评论.
If this is unclear, it's because I don't completely understand the mechanism. If you have a better grasp of what's going on here, please comment below.
这篇关于如何在 AppleScript 的处理程序中有效地构建列表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!