ns-2的TCL脚本中的过程内无法识别全局变量

时间:2013-02-14 09:40:56

标签: global-variables tcl ns2

我正在尝试运行以下tcl脚本,但在程序thpt_rec中出现错误 ns:thpt_rec:无法读取“tcps(0)”:没有这样的变量
    执行时 “$ tcps(0)set bytes_”
    (程序“thpt_rec”第4行)
    从内部调用 “thpt_rec”

但是当我在所有地方用一个名为sink的变量替换这个tcps(0)时,一切都运行良好。请明白这个问题。

set ns [new Simulator]  
set tracefile [open tcpf1.tr w]  
set thptfile  [open thpt.tr  w]   
$ns trace-all $tracefile

proc finish {} {  
global ns tracefile thptfile  
$ns flush-trace  
close $tracefile  
close $thptfile  
exit 0  
}

proc thpt_rec {} {  
global ns tcps(0) thptfile  
set time 1.0   
set bw [$tcps(0) set bytes_]  
set now [$ns now]  
puts $thptfile "$now [expr $bw/$time*8/1000000]"  
$tcps(0) set bytes_ 0  
$ns at [expr $now+$time] "thpt_rec"     
}

for {set i 0} {$i < 10} {incr i} {  
set n($i) [$ns node]  
}

for {set i 0} {$i < 4} {incr i} {  
$ns duplex-link $n($i) $n(4) 10Mb 2ms DropTail  
$ns duplex-link $n(5)  $n([expr ($i+6)]) 10Mb 2ms DropTail   
}

$ns duplex-link $n(4) $n(5) 0.25Mb 10ms DropTail

set tcp(0) [new Agent/TCP]  
$ns attach-agent $n(0) $tcp(0)  
set tcps(0) [new Agent/TCPSink]  
$ns attach-agent $n(6) $tcps(0)  
$ns connect $tcp(0) $tcps(0)  
set ftp(0) [new Application/FTP]     
$ftp(0) attach-agent $tcp(0)  

$ns at 0.0 "thpt_rec"  
for {set i 0} {$i < 1} {incr i} {  
$ns at [expr (5.0 * $i )] "$ftp($i) start"  
$ns at 140.0 "$ftp($i) stop"  
}  
$ns at 150.0 "finish"  

$ns run

1 个答案:

答案 0 :(得分:4)

替换

global ns tcps(0) thptfile

global ns tcps thptfile

它应该可以正常工作。

问题是tcps变量是array数组元素不是变量 - 它们只是值。所以如果如果要在过程中访问全局数组的元素,则应将数组变量本身声明为global