Version 4 of Tcl variable scope - how does Tcl control when a variable is seen?

Updated 2004-07-08 19:11:01 by lwv

I was noticing a discussion on comp.lang.tcl about variable scope and when I searched the wiki, I didn't notice quickly any place where the topic of scope was centrally discussed.

Tcl has several layers of scoping - from an article by Bryan Oakley, we read:

 Sektor van Skijlen wrote:
 > Could someone explain me, what is the proper syntax with correct scope for
 > variables, which are:
 > 
 >  - declared inside in a namespace

variable varname ?initValue?

 >  - globally

global varname ?varname ...?


LV With the advent of namespaces, one can provide a more consistent variable usage by using ::varname as opposed to invoking the global command with varname.

RHS However, if you're accessing the variable a lot, its worth using the global command, since it is faster to access the variable that way. Assuming performance matters in what you are doing.

 % proc p1 {} { global v1 ; for {set i 0} {$i <1000} {incr i} { set v1 } }
 % proc p2 {} {for {set i 0} {$i <1000} {incr i} { set ::v2 } }
 % time { p1 } 100
 1802 microseconds per iteration
 % time { p2 } 100
 4520 microseconds per iteration

LV Curious - is it due to additional parsing? Or is tcl just missing an optimization?


> - accessed in a proc defined in the same namespace

use variable if you wish to reference the namespace variable, global if you want to reference the global variable. Use neither to reference a local variable.


Please add other information, discussion, corrections to this page.


Note that merely declaring a variable with the global or variable command does NOT create the variable. It just tells Tcl where to go looking for the variable if there's a reference to it.


Category Tutorial