这句话有什么问题

时间:2011-04-18 09:00:21

标签: tcl

        for {set count 0} {$count<$num_of_UEs} { incr count } {
            puts $count
            set tcp$count [new Agent/TCP]
            #$tcp$count set fid_ $count
            #$tcp$count set prio_ 2

    }

我的问题在于行#$tcp$count set fid_ $count 当我尝试执行它时,它说

 can't read "tcp": no such variable
    while executing
"$tcp$count set fid_ $count"
    ("for" body line 4)
    invoked from within
"for {set count 0} {$count<$num_of_UEs} { incr count } {
                                puts $count
                                set tcp$count [new Agent/TCP]
                                $tcp$count set fid_ $count
                                $tcp$coun..."

它说无法读取tcp,它不应该读取tcp它应该在第一次迭代中读取为tcp0而在第二次迭代中读取tcp1,依此类推。 我做错了什么?

感谢

编辑:

我尝试使用数组,感谢TIP。它适用于大多数部件,但在一个特定情况下 当我这样做时:

    for {set count 0} {$count<$num_of_UEs} { incr count } {
    set ftp($count) [new Application/FTP]
    $ftp($count) attach-agent $tcp($count)
    }

它给了我以下错误:

Came here 0

    (_o180 cmd line 1)
    invoked from within
"_o180 cmd target _o99"
    invoked from within
"catch "$self cmd $args" ret"
    invoked from within
"if [catch "$self cmd $args" ret] {
set cls [$self info class]
global errorInfo
set savedInfo $errorInfo
error "error when calling class $cls: $args" $..."
    (procedure "_o180" line 2)
    (SplitObject unknown line 2)
    invoked from within
"$agent target [[$self node] entry]"
    (procedure "_o98" line 2)
    (RtModule attach line 2)
    invoked from within
"$m attach $agent $port"
    (procedure "_o97" line 4)
    (Node add-target line 4)
    invoked from within
"$self add-target $agent $port"
    (procedure "_o97" line 15)
    (Node attach line 15)
    invoked from within
"$node attach $agent"
    (procedure "_o3" line 2)
    (Simulator attach-agent line 2)
    invoked from within
"$ns attach-agent $node2 $tcp($count)"
    ("for" body line 3)
    invoked from within
"for {set count 0} {$count<$num_of_UEs} { incr count } {
                puts "Came here $count"
                $ns attach-agent $node2 $tcp($count)
                }"
    (file "hsexample.tcl" line 104)

我知道它很长,但我非常感谢你的帮助

3 个答案:

答案 0 :(得分:6)

问题是在$之后解析变量名称会停在第一个非字母数字字符处(除了我稍后会提到的情况)。这意味着$tcp$count被解释为字符串,它是tcp变量和count变量(只有您定义的一个)的内容的串联。

处理此问题的最佳方法是使用Tcl的关联数组:

for {set count 0} {$count<$num_of_UEs} { incr count } {
    puts $count
    set tcp($count) [new Agent/TCP]
    $tcp($count) set fid_ $count
    $tcp($count) set prio_ 2
}

(是变量访问语法处理的一个特例;它开始处理一个关联数组访问(继续匹配),假设没有不带引号的空格)。

(变量名中的另一个特例是::,这是Tcl的命名空间分隔符。)

答案 1 :(得分:0)

如果您这样做,则试图获取(不存在的变量)tcp的内容和变量count的内容。你想要的是获得tcp$count的内容。您可以使用set命令实现此目的。只需:

[set tcp$count] set fid_ $count

答案 2 :(得分:0)

我的大错误追溯,我看到了:

if [catch "$self cmd $args" ret] {

你真的有一个名为“cmd”的实例方法(或者你似乎使用的OO系统的任何术语)

你想要:

if {[catch {$self $cmd $args} ret]} { ...