Reputation:
I have a question about variable scope in TCL, I have the following code:
namespace eval ::hello {
variable player
variable name
namespace export *
}
proc ::hello::setPlay {value} {
set ::hello::player
}
proc ::hello::getPlay {} {
return $::hello::player
}
proc ::hello::setName {value} {
set ::hello::name
}
proc ::hello::getName {} {
return $::hello::name
}
proc GET_NAME {} {
#here I have a variable called name as well
set name "RON"
return $name
}
in the GET_NAME,if I set the variable name as "RON", does it will set the variable name declaired in namespace? can I have the same variable name in GET_NAME and namespace? And if I add this line variable name
in GET_NAME, does this mean, it will set the variable declaired in name space?
Upvotes: 1
Views: 1114
Reputation: 137557
Variables in procedures (and lambda expressions) default to being local to that procedure. If explicitly declared to be something else (e.g., with global
, upvar
or variable
) then that actually couples a local variable to another variable elsewhere so that acting on one (e.g., reading or writing) is exactly like acting on the other. If you use a variable name with ::
in it, that is a reference to a namespaced variable (the global namespace is just ::
) which might be resolved either relative to the current namespace or the global namespace, depending on whether the name starts with ::
or not. (Think of it a bit like a slash in a filename.)
When executing code inside namespace eval
, always use variable
to declare variables before using them. This avoids problems with global variable shadowing that are really horrible but necessary to keep due to some existing code depending on them. (Technically, you don't need to do this in namespace eval ::
as global variables can't shadow themselves, but it doesn't hurt.)
Dealing with specifics:
in the GET_NAME,if I set the variable name as "RON", does it will set the variable name declaired in namespace?
No, not with the code you wrote.
can I have the same variable name in
GET_NAME
and namespace?
You can use the same name of variable in the two places. This can be confusing, but it limits surprises overall.
And if I add this line
variable name
inGET_NAME
, does this mean, it will set the variable declaired in name space?
Yes. Exactly that. (It couples the two together precisely.)
Upvotes: 5