代码之家  ›  专栏  ›  技术社区  ›  outis

在applescript中,为什么处理程序中的局部变量捕获“with”标记的参数?

  •  0
  • outis  · 技术社区  · 14 年前

    在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 
    

    导致在第二行中未定义“scnd”的错误消息 bam . thing frst 都已定义,正在将调用中传递的参数 巴姆 . 为什么会这样?为什么是 scnd 未定义?

    注意:我知道在处理程序中声明变量为“局部”是不必要的。为了便于说明,在示例中进行了这样的操作。

    这里还有一些不抛出错误的例子,说明了什么变量得到什么值。为了区分第一个和第二个给定参数,调用每个处理程序 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}}
    
    1 回复  |  直到 14 年前
        1
  •  1
  •   outis    14 年前

    在玩了一会儿之后,答案似乎是使用 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}}