Reputation: 165
i want to use the variable assigned outside (proc) to be used inside the proc . For example i tried the following thing
set a 10
proc myproc { } {
puts $a
}
myproc
I am expecting the above script to print 10 . But the above script is erroring out "can't read "a": no such variable"
I cannot pass $a as argument to script because i have lot such variables i want to use inside my proc inside my script . Could you please help me to solve this problem ?
Your help is appreciated
Upvotes: 0
Views: 1811
Reputation: 33
If you have namespaces you could always assign it there :
namespace eval blah {
variable a 10
}
proc blah::myproc { } {
variable a
puts $a
}
blah::myproc
This way you can avoid potential collisions with other global variables
Upvotes: 0
Reputation: 6017
If the variable is declared at the same stack level as the call to myproc
then you can do following in your proc:
upvar a a
like this:
set a 10
proc myproc { } {
upvar a a
puts $a
}
myproc
and then you can use $a
locally in the procedure. The upvar
command "links" a variable declared somewhere in the stack with a local variable. If the variable is declared more than 1 level deeper in the stack, thn you need to pass "2" to upvar
, so it knows where to look for the variable:
upvar 2 a a
If you don't pass the "2" (or other value), the upvar
assumes default lookup depth of 1.
You can read more details about upvar
in Tcl documentation for that command.
If the variable a
is always a global variable (declared at the script top level), then you can use:
global a
in your procedure, instead of upvar
.
Upvotes: 2