| View previous topic :: View next topic |
| Author |
Message |
CrazyCat Revered One

Joined: 13 Jan 2002 Posts: 1032 Location: France
|
Posted: Wed Mar 23, 2022 11:36 am Post subject: Accessing a [namespace current] variable |
|
|
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: | 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  _________________ https://www.eggdrop.fr - French IRC network
Offer me a coffee - Do not ask me help in PM, we are a community. |
|
| Back to top |
|
 |
caesar Mint Rubber

Joined: 14 Oct 2001 Posts: 3741 Location: Mint Factory
|
Posted: Wed Mar 23, 2022 12:29 pm Post subject: |
|
|
| Code: |
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: |
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. |
|
| Back to top |
|
 |
SpiKe^^ Owner

Joined: 12 May 2006 Posts: 792 Location: Tennessee, USA
|
Posted: Wed Mar 23, 2022 12:38 pm Post subject: |
|
|
The common method using [variable] similar to [global].... | Code: | proc readit {} { ;# common method
variable v
putlog "v is now $v"
} |
Another method I find handy....
| Code: | 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
. |
|
| Back to top |
|
 |
CrazyCat Revered One

Joined: 13 Jan 2002 Posts: 1032 Location: France
|
Posted: Wed Mar 23, 2022 1:22 pm Post subject: |
|
|
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 _________________ https://www.eggdrop.fr - French IRC network
Offer me a coffee - Do not ask me help in PM, we are a community. |
|
| Back to top |
|
 |
|