This is the new home of the egghelp.org community forum.
All data has been migrated (including user logins/passwords) to a new phpBB version.


For more information, see this announcement post. Click the X in the top right-corner of this box to dismiss this message.

Accessing a [namespace current] variable

Help for those learning Tcl or writing their own scripts.
Post Reply
User avatar
CrazyCat
Revered One
Posts: 1305
Joined: Sun Jan 13, 2002 8:00 pm
Location: France
Contact:

Accessing a [namespace current] variable

Post by CrazyCat »

Hi there,

I've a little trouble with a script I'm writing. I'm trying to do it really modular with the minimum of hardcoded things.

The code looks like (just an example):

Code: Select all

namespace eval myns {

   variable v 

   proc doit {} {
      # This works
      incr [namespace current]::v 1
   }

   proc readit {} {
      # this fails
      putlog "v is now $[namespace current]::v"
   }
}
The proc readit doesn't work, I can't figure out how to access $::myns::v using [namespace current]. All ideas are welcome :)
User avatar
caesar
Mint Rubber
Posts: 3778
Joined: Sun Oct 14, 2001 8:00 pm
Location: Mint Factory

Post by caesar »

Code: Select all

namespace eval myns {
	variable v
	proc doit {} {
		incr [namespace current]::v
	}
	proc readit {} {
		variable v
		putlog "v is now $v"
   }
}
Or you can use upvar:

Code: Select all

namespace eval myns {
	variable v
	proc doit {} {
		incr [namespace current]::v 1
	}
	proc readit {} {
		upvar 1 [namespace current]::v v
		putlog "v is now $v"
   }
}
Btw, there's no need for the '1' in the incr line as by default it increments with one.
Once the game is over, the king and the pawn go back in the same box.
User avatar
SpiKe^^
Owner
Posts: 831
Joined: Fri May 12, 2006 10:20 pm
Location: Tennessee, USA
Contact:

Post by SpiKe^^ »

The common method using [variable] similar to [global]....

Code: Select all

    proc readit {} {   ;# common method 
       variable v
       putlog "v is now $v" 
    } 

Another method I find handy....

Code: Select all

    proc readit {} { 
       # another method
       putlog "v is now [set [namespace current]::v]" 
    } 
SpiKe^^

Get BogusTrivia 2.06.4.7 at www.mytclscripts.com
or visit the New Tcl Acrhive at www.tclarchive.org
.
User avatar
CrazyCat
Revered One
Posts: 1305
Joined: Sun Jan 13, 2002 8:00 pm
Location: France
Contact:

Post by CrazyCat »

Thanks guys.

I'll probably use the last method from SpiKe^^ as I'll have to use [namespace parent] sometimes.

Using upvar is a way I'd looked, but it's less flexible imho
Post Reply