user976754
user976754

Reputation: 361

Global variable is not recognized inside a procedure in TCL script for ns-2

I am trying to run the following tcl script but getting an error in procedure thpt_rec that
ns: thpt_rec: can't read "tcps(0)": no such variable
while executing
"$tcps(0) set bytes_"
(procedure "thpt_rec" line 4)
invoked from within
"thpt_rec"

But when I replace this tcps(0) with a variable named sink at all place everything works well. Kindly shed light in this issue.

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

Upvotes: 1

Views: 2001

Answers (1)

kostix
kostix

Reputation: 55443

Replace

global ns tcps(0) thptfile

with

global ns tcps thptfile

and it should work OK.

The problem is that the tcps variable is an array, and array elements are not variables — they are just values. So if you want to access an element of a global array in a procedure, you should declare the array variable itself as global.

Upvotes: 4

Related Questions