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
}
Run Code Online (Sandbox Code Playgroud)
我的问题在于线路#$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..."
Run Code Online (Sandbox Code Playgroud)
它说无法读取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)
}
Run Code Online (Sandbox Code Playgroud)
它给了我以下错误:
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)
Run Code Online (Sandbox Code Playgroud)
我知道它很长,但我真的很感谢你的帮助
问题是$在第一个非字母数字字符停止后解析变量名称(我稍后会提到的情况除外).这意味着它$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
}
Run Code Online (Sandbox Code Playgroud)
这(是变量访问语法处理的一个特例; 它开始处理一个关联数组访问(继续进行匹配),假设没有未引用的空格).
(变量名中的另一个特例::是Tcl的命名空间分隔符.)