Difference between upvar 0 and upvar 1 in TCL -
can let me know difference between upvar 0
, upvar 1
in tcl, how can use in real time. kindly, if explain example, makes me more clear.
when calling bunch of procedures, stack of stack frames. it's in name. might visualise so:
abc 123 456 bcd 321 456 cde 654 321
ok, we've got abc
calling bcd
calling cde
. simple.
the 0
, 1
in upvar
how many levels go stack when looking variable link to. 1
means go 1 level (i.e., caller of current frame), cde
bcd
in our example, 2
go cde
abc
, 3
way global evaluation level overall scripts , callbacks run. 0
special case of this; means lookup in current stack frame. there's ability use indexing base of stack putting #
in front of name, #0
indicates global frame, #1
first thing calls.
the common use of upvar
upvar 1
(and if leave level out, that's does). upvar 0
used when want different (usually easier work with) name variable. next common 1 upvar #0
, though global
more common shorthand there (which matches unqualified parts of name convenience). other forms rare; example, upvar 2
indication of confusing , tangled code, , hardly ever used upvar #1
before tcl 8.6's coroutines. i've never seen upvar 3
or upvar #2
in wild (though computed level indicators present in object systems tcl).
example of upvar 1
— pass variable name:
proc mult-by {varname multiplier} { upvar 1 $varname var set var [expr {$var * $multiplier}] } set x 2 mult-by x 13 puts "x $x" # x 26
example of upvar 0
— simplify variable name:
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"
Comments
Post a Comment