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

Updated 2004-07-08 13:44:11 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.


> - 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