Google Groups no longer supports new Usenet posts or subscriptions. Historical content remains viewable.
Dismiss

Difference between set and variable command in namespace

395 views
Skip to first unread message

gagan kandra

unread,
Jan 29, 2014, 1:03:40 AM1/29/14
to
I am trying to set a variable inside a namespace using set command but when i am accessing outside the namespace it is unable to find that variable whereas if i am using variable command it is able to find the variable name. So what is the difference b/w variable and set command . Here is the script which works fine on tclsh but not in my code.

namespace eval ::gk:: {
variable library [file dirname [info script]]
}

puts " gk library == $::gk::library"

namespace eval ::snit:: {
set library [file dirname [info script]]
}
puts "snit library == $::snit::library"


Output of above script is fine in tclsh but in my code first puts works fine but second puts gives error

can't read "::snit::library": no such variable


Please tell me what is difference and what is wrong with namespace in my code.

Emiliano

unread,
Feb 6, 2014, 12:57:03 PM2/6/14
to

Donal K. Fellows

unread,
Feb 6, 2014, 1:34:08 PM2/6/14
to
On 29/01/2014 06:03, gagan kandra wrote:
> Please tell me what is difference and what is wrong with namespace in my code.
>

The difference between [variable foo $bar] and [set foo $bar], when
called from inside a [namespace eval], depends on whether the variable
called 'foo' exists in the current namespace beforehand. If the variable
exists, they behave the same. If the variable *doesn't*, things get more
complex.

With [variable], the named variable is created in the current namespace.
This occurs even if you don't supply a value (though in that case the
variable is created in the unset state.)

With [set], the variable is looked up in the global namespace (or
wherever else the current variable resolver dictates, but the default is
simple) and if that exists, that variable is used instead. Otherwise,
the variable is created in the current namespace. The [set] command is
not special in this way; [array set], [lappend], and in fact nearly
anything that works with variables is the same; only [variable],
[upvar], [global] and [namespace upvar] are different.

Because you really do not want the craziness, use [variable] to declare
the variables in your namespaces before you use them. (This doesn't
apply to the global namespace or to local variables, which is why most
people don't notice, or — I think — to TclOO-driven namespaces which use
a custom resolver that isn't so crazy.)

Donal.
--
Donal Fellows — Tcl user, Tcl maintainer, TIP editor.
0 new messages