Node:Global variables, Next:source, Previous:User defined procedures, Up:Commands
A word about the scope of variables. Variables used within procedures are normally created only for the duration of that procedure and have local scope.
It is possible to declare a variable as having global scope, through the
global
command:
global name1 ? name2 ...?
where name1, name2, ..., are the names of global variables. Any references to those names will be taken to denote global variables for the duration of the procedure call.
Global variables are those variables declared at the topmost calling
context. It is possible to run a global
command at anytime in a
procedure call. After such a command, the variable name will refer to a global
variable until the procedure exits.
An example:
set x 10 proc fred { } { set y 20 global x puts [expr $x + $y] } fred
will print the result 30
where 20 comes from the local variable
y
and 10 comes from the global variable x
.
Without the global x
line, the call to fred
will fail with
an error because there is no variable x
defined locally in the
procedure for the expr
to evaluate over.