Reputation: 750
I have my tcl code like below,
set n0 [$ns node]
$n0 set X_ 284
$n0 set Y_ 380
$n0 set Z_ 0.0
$ns initial_node_pos $n0 20
set n1 [$ns node]
$n1 set X_ 343
$n1 set Y_ 195
$n1 set Z_ 0.0
$ns initial_node_pos $n1 20
Then I added for{ } loop
to assign TCP connection for every node:
for {set i 0} { $i < 10} {incr i} {
set tcp1 [new Agent/TCP]
$ns attach-agent $n$i $tcp1
}
It shows the error like,
can't read "n": no such variable
while executing
"$ns attach-agent $n$i $tcp1"
("for" body line 4)
invoked from within
"for {set i 0} { $i < 10} {incr i} {
set tcp1 [new Agent/TCP]
$ns attach-agent $n$i $tcp1
}
When I use $n($i)
instead of $n$i
it works fine. Is there any way to use variable $n$i
in tcl?
Upvotes: 1
Views: 100
Reputation: 137567
When you pass only one argument to set
, it reads the named variable (instead of writing to it, which is what happens when you pass in two arguments).
$ns attach-agent [set n$i] $tcp1
As you already know, if you're doing this then you probably ought to use an array instead. It's really much simpler.
The other possibility (trickiness incoming!) is to create a local alias variable with a simple literal name:
upvar 0 n$i thisN
$ns attach-agent $thisN $tcp1
Be aware that once you use upvar 0
you can't make that alias variable be an ordinary variable except by ending the context (stack frame, namespace) containing the alias variable. But you can redirect the alias to another variable by using upvar 0
again.
Upvotes: 2