Tcl 如何在proc中声明可选参数
你能帮助我如何使用参数和选项吗?我使用了这个函数,但它不起作用Tcl 如何在proc中声明可选参数,tcl,Tcl,你能帮助我如何使用参数和选项吗?我使用了这个函数,但它不起作用 proc {my_proc} {n1 n2 -args{{u2 "5"} {u1 "5"}} } { puts "n1:'$n1', n2:'$n2', u1:'$u1', u2:'$u2'" } ->my_proc 1 -args 5 7 n1:'1', n2:'$n2', u1:'7', u2:'5' 我想调用如下函数 my_proc 1-args{u2 5}{u1 7} my_proc 1{u2 5}{u1 7}(
proc {my_proc} {n1 n2 -args{{u2 "5"} {u1 "5"}} } {
puts "n1:'$n1', n2:'$n2', u1:'$u1', u2:'$u2'"
}
->my_proc 1 -args 5 7
n1:'1', n2:'$n2', u1:'7', u2:'5'
我想调用如下函数
my_proc 1-args{u2 5}{u1 7}
my_proc 1{u2 5}{u1 7}(必需+可选参数)
my\u proc 1(仅限必需参数)
dict set options$args;卖出$options(-u1)
。这些在Tcl 8.4(以及之前的版本,对于真正落后的时代)中特别有用:
正如Donal所建议的,我喜欢使用
args
和一个数组来处理选项。它提供了一种设置默认值的简单方法:
proc p {args} {
array set options {-u1 defU1 -u2 defU2} ;# the default values
array set options $args ;# merge the user's values
parray options
}
p -foo bar -u1 42
您需要检查$args是否包含偶数个元素:
% p 1 2 3
list must have an even number of elements
在这种情况下,使用
args
作为最后一个参数名并解析该列表的内容。我尝试了上述方法,但在TCL版本中出现了错误:无效的命令名“dict”(TCL)@user3069844 Nodict
?您一定有一个非常旧的Tcl版本。我正在designer工具中使用TCLVersion8.4
proc my_proc {n1 n2 args} {
# Defaults
array set opt {-u1 5 -u2 5}
# Parse
array set opt $args
# Use
puts "n1:'$n1', n2:'$n2', u1:'$opt(-u1)', u2:'$opt(-u2)'"
}
my_proc 7 8 -u1 123 -u2 456
#### n1:'7', n2:'8', u1:'123', u2:'456'
proc p {args} {
array set options {-u1 defU1 -u2 defU2} ;# the default values
array set options $args ;# merge the user's values
parray options
}
p -foo bar -u1 42
options(-foo) = bar
options(-u1) = 42
options(-u2) = defU2
% p 1 2 3
list must have an even number of elements