我有一个变量,我想将其用作参数的默认值:
proc log {message {output $::output}} {
....
}
有没有办法做到这一点或需要我评估我的proc中的变量?
我有一个变量,我想将其用作参数的默认值:
proc log {message {output $::output}} {
....
}
有没有办法做到这一点或需要我评估我的proc中的变量?
是的,但您不能在参数列表中使用花括号 ( {}
)。您以这种方式声明程序,例如:
proc log [list message [list output $::output]] {
....
}
但请注意:
变量是在声明过程时计算的,而不是在执行时计算的!
如果您想要一个仅在调用时在 value 中定义的默认参数,则必须更加棘手。关键是您可以使用它info level 0
来获取当前过程调用的参数列表,然后您只需检查该列表的长度:
proc log {message {output ""}} {
if {[llength [info level 0]] < 3} {
set output $::output
}
...
}
请记住,在检查参数列表时,第一个是命令本身的名称。
另一种方法:
proc log {message {output ""}} {
if {$output eq ""} {
set output $::output
}
}