Tcl - global, upvar and uplevel.
Archive - Originally posted on "The Horse's Mouth" - 2007-10-24 08:16:15 - Graham EllisIn Tcl, variables are "scoped" to the procedure in which they're used. That's a sensible default, since you want to be able to write main applications without the risk of interfering with variables within your procs.

An upvar command allows you to reference a variable in your calling code from within your proc, and is commonly used for "pass by name" requirements where you're writing a proc that must alter an incoming variable.
The uplevel command allows you to run a piece of code as if it was in the namespace of your calling code and not in your proc - and you can even specify a number of levels of code up or an absolute level number.
Suggestion. Use upvar whenever you need to call by name. Use global sparingly. And think very carefully before you ever use uplevel!
Example:
proc demo {what where} {
global counter
upvar $where hereitis
uplevel incr dc
append hereitis ", UK"
incr counter
puts "Demo run"
return "$what $hereitis"
}
#
set dc 0
set counter 0
set place Melksham
set rz [demo "eat in" place]
puts "function returns: $rz"
puts "place will have UK on the end: $place"
puts "counter is number of calls to demo: $counter"
puts "variable dc has become: $dc"
Runs as
Dorothy:~/oct07 grahamellis$ tclsh uld
Demo run
function returns: eat in Melksham, UK
place will have UK on the end: Melksham, UK
counter is number of calls to demo: 1
variable dc has become: 1
Dorothy:~/oct07 grahamellis$