Difference between upvar 0 and upvar 1 in TCL

Can someone tell me the difference between upvar 0and upvar 1in TCL, as we can use in real time. Please, if someone explains with an example, this makes me more understandable.

+4
source share
3 answers

When you call a bunch of procedures, you get a stack of stack frames. It is in the title. We could visualize it like this:

abc 123 456
   bcd 321 456
      cde 654 321

OK, so we have a abccall bcdcalling cde. Plain.

0 1 upvar , , . 1 ( ), cde bcd , 2 cde abc 3 , . 0 - ; , . , # , #0 , #1 , .

upvar upvar 1 ( , ). upvar 0 , ( ) . - upvar #0, global - ( ). ; , upvar 2 , - - upvar #1 , Tcl 8.6 . upvar 3 upvar #2 ( Tcl).

upvar 1 - :

proc mult-by {varName multiplier} {
    upvar 1 $varName var
    set var [expr {$var * $multiplier}]
}

set x 2
mult-by x 13
puts "x is now $x"
# x is now 26

upvar 0 - :

proc remember {name contents} {
    global my_memory_array
    upvar 0 my_memory_array($name) var
    if {[info exist var]} {
        set var "\"$var $contents\""
    } else {
        set var "\"$name $contents\""
    }
}

remember x 123
remember y 234
remember x 345
remember y 456
parray my_memory_array
# my_memory_array(x) = ""x 123" 345"
# my_memory_array(y) = ""y 234" 456"
+8

upvar 1, upvar 0 . ex:

    set a 4 
proc upvar1 {a} {
upvar 1 a b
incr a 4
incr b 3
puts "output is $a $b"
}
proc upvar0 {a} {
upvar 0 a b
incr a 4
incr b 3
puts "output is $a $b"
}
upvar1 $a
puts "in global frame value of a is  $a"

set a 4
upvar0 $a
puts "in global frame value of a is  $a"

:

output is 8 7
in global frame value of a is  7
output is 11 11
in global frame value of a is  4
+2

, , :

Suppose we have a test_upvar1 function:

proc test_upvar1 {} {
    upvar 1 a b
    incr b
}

And the function test_upvar0:

proc test_upvar0 {} {
    upvar 0 a b
    incr b
}

Now we set the variable a and call both functions to see what happens:

set a 5
test_upvar1

This will return 6

set a 5
test_upvar0

Will be back 1

This is because we select with zero and one of our execution frames 0 in one execution frame 1 in the frame above.

See http://wiki.tcl.tk/1508

+1
source

All Articles