Dionis Beqiraj
Dionis Beqiraj

Reputation: 797

Variable assignment inside procedures. Tcl

I have this example:

set ns [new Simulator]
set var 0
proc proc1{var}{
  set $var 2
}
proc proc2{var}{
  puts stdout $var
  # I want $var to be 2, but it is 0.
}
$ns at 1 "proc1 $var"
$ns at 5 "proc2 $var"

So, can anyone help me please?

Upvotes: 1

Views: 104

Answers (1)

Donal Fellows
Donal Fellows

Reputation: 137567

You want to work with the variable itself, not copies of it's contents taken at the time that the timer callbacks were created. In this case, you should not pass the variable in as an argument, but rather refer to the global variable directly. Like this:

# Omitting the setup parts that are identical...
proc proc1 {} {
    global var
    set var 2
}
proc proc2 {} {
    global var
    puts stdout $var
}
$ns at 1 "proc1"
$ns at 5 "proc2"

If you don't say global (or one of the other commands for accessing out of the scope, such as variable or upvar) the variable that you work with will be purely local to the procedure's stack frame.

Upvotes: 4

Related Questions