Version 4 of Useful tools for namespaces

Updated 2013-06-08 20:41:55 by Larry

This is an empty page.

I've been using namespaces to structure data of late, and I've generated a few procedures I thought others might find helpful. One annoying thing is the variable command - you can't just give it a list of variables you want the code to access in a namespace, you have to have multiple variable statements, one for each, as the semantics don't take a list per se but must alternate with an initializer. With:

 proc vars { args } {
   foreach var $args {
     uplevel "variable $var"
   }
 }

You can say

 vars a b c

and that is the equivalent of

 variable a
 variable b
 variable c

A minor convenience but makes for more concise code.

Not infreguently, I find myself wanting to execute something in a namespace but to access vars in a surrounding proc context. Using {} defeats just calling $whatever in the namespace since the proc variables are not visible. You either have to use " and " - thereby putting one in quoting hell - or you have to have a prefix and body where the prefix is done with quotes and then appended to the body, to pass in vars. Here's a nicer way to do that:

 proc access { args } {
   foreach var $args {
     set t [split $var >]
     if {[llength $t] == 2} {
       set left [lindex $t 0]
       set right [lindex $t 1]
     } else {
       set left $var
       set right $var
     }
     set temp "[uplevel uplevel set $left]"
     regsub -all {"} $temp {\"} temp
     set cmd "set $right \"$temp\""
     uplevel $cmd
   }
 }

with this you can do:

 proc foobar { this that args } {
   namespace eval foo {
     access args this that
     set arglist $args
     puts "I was passed $this and $that"
   }
 }

and it works as expected. Access also allows you to rename things.

 proc foobar { this that args } {
   namespace eval foo {
     access args>arglist this>mythis that>mythat
     puts "I was passed $arglist $mythis and $mythat"
   }
 }