【问题标题】:Set 2 default variables in a tcl procedure在 tcl 过程中设置 2 个默认变量
【发布时间】:2016-06-14 00:21:12
【问题描述】:

当在 tcl 中定义一个像下面这样的过程时,我如何调用只定义 a 和 c 的 proc?有没有办法做到这一点?

proc test1 { a {b 2} {c 3} } {
   puts "$a $b $c"
}

【问题讨论】:

  • 不。你不能跳过这个论点。
  • 有没有办法提供 2 个或多个默认值?

标签: tcl proc


【解决方案1】:

这是一种技术,比你所希望的有点混乱,但不是太混乱:

proc test1 { args } {
    # set the default values
    array set values {b 2 c 3}

    # todo: validate that $args is a list with an even number of items

    # now merge in the args
    array set values $args

    # and do stuff with the values ...
    parray values
}

test1 a 10 c 14

您有时会看到应用程序使用这种技术,其中数组键有一个前导破折号,看起来像选项:

proc test1 args {
    array set values {-b 2 -c 3}
    array set values $args
    parray values
}

test1 -a 10 -c 14

【讨论】:

  • 如果需要说明,a 仍然可以使用{a args} 作为必填参数。如果仍然希望a 出现在values 中,请使用(例如)array set values [list a $a b 2 c 3]
【解决方案2】:

感谢 Glenn 和 Peter,我加入了你的帖子并得到了

proc test1 { a args } {
    array set valores [list a $a  -b 2 -c 3]
    array set valores $args
    puts "$valores(a) $valores(-b) $valores(-c)" 
}

这解决了我想要的。

所以现在我可以打电话了

> proc 12 -c 8
> 12 2 8

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-01-04
    • 2015-08-18
    • 1970-01-01
    • 1970-01-01
    • 2016-10-01
    • 2017-01-02
    • 2017-01-16
    相关资源
    最近更新 更多