在Applescript中,如果使用带有“with”标记的参数声明处理程序,则局部变量将获取参数的值,并且参数本身未定义。例如:
on bam of thing with frst and scnd
local eat_frst
return {thing: thing, frst:frst, scnd:scnd} -- this line throws an error
end bam
bam of "bug-AWWK!" with frst without scnd
会导致错误消息“{scan”未在bam
的第二行中定义。 thing
和frst
都已定义,将调用中的参数传递给bam
。为什么会这样?为什么scnd
未定义?
注意:我知道在处理程序中将变量声明为“local”是不必要的。为了说明的目的,它在示例中完成。
以下是一些不会抛出错误的示例,说明了哪个变量获得了什么值。为了区分第一和第二给定参数,每个处理程序被调用with
第一个给定参数,without
第二个给定参数。请注意,使用given userLabel:userParamName
语法没有值捕获问题。
on foo of thing given frst:frst_with, scnd:scnd_with
local eat_nothing
return {frst:frst_with, scnd:scnd_with}
end foo
on bar of thing with frst and scnd
local eat_frst
return {frst:eat_frst, scnd:scnd}
end bar
on baz of thing with frst and scnd
eat_frst
local eat_scnd, eat_others
return {frst:eat_frst, scnd:eat_scnd}
end baz
{foo:(foo of "foo" with frst without scnd), ¬
bar:(bar of "bar" with frst without scnd), ¬
baz:(baz of "baz" with frst without scnd)}
结果:
{ foo:{frst:true, scnd:false}, bar:{frst:true, scnd:false}, baz:{frst:true, scnd:false}}
答案 0 :(得分:1)
使用它后,答案似乎是使用with
标记的参数不会引入变量。相反,值按照它们在处理程序主体中遇到的顺序分配给局部变量。
说明性示例:
on baa of thing with frst and scnd
scnd
frst
return {frst:scnd, scnd:frst}
end baa
on bas of thing with frst and scnd
-- note that eat_frst gets the value of the frst parameter,
-- then gets set to "set"
set eat_frst to "set"
eat_scnd
return {frst:eat_frst, scnd:eat_scnd}
end bas
on qux of thing with frst and scnd
if scnd then
end if
local eat_scnd, eat_others
return {frst:scnd, scnd:eat_scnd}
end qux
on quux of thing with frst and scnd
if frst then
end if
if eat_scnd then
end if
return {frst:frst, scnd:eat_scnd}
end quux
{ baa: (baa of "baa" with frst without scnd), ¬
bas: (bas of "bas" with frst without scnd), ¬
qux: (qux of "qux" with frst without scnd), ¬
quux: (qux of "qux" with frst without scnd) }
结果:
{ baa:{frst:true, scnd:false}, bas:{frst:"set", scnd:false}, qux:{frst:true, scnd:false}, quux:{frst:true, scnd:false}}