Version 3 of Alternative Namespaces

Updated 2006-02-15 14:33:57

MJ - I was reading the page at [L1 ] and decided to try to implement some of the described behaviour using Tcl. The nice thing about the way namespaces work in the example below is that simply executing the namespace name (e.g. [win32]) displays all the methods in that namespace. This would be great for IDE autocompletion.

Note that because of the usage of {expand} this code requires at least Tcl 8.5 to run.


 # this code creates 3 namespaces: {win32}, {win32 media} and {string} 

 proc {win32 ping} {host} {
         puts "Sending ping to host $host"
 }


 proc {win32} {args} {
   set namespace [lindex [info level 0] 0]
         if { [llength $args]==0 } {
                 puts "[info procs [concat $namespace *]]"
         } else {
            "$namespace [lindex $args 0]" {expand}[lrange $args 1 end]
         }
 }

 proc {win32 media play} {song} {
   puts "playing song $song"
 }

 proc {win32 media beep} {length} {
         puts "beeping for $length"        
 }

 proc {win32 media} {args} {
   set namespace [lindex [info level 0] 0]
         if { [llength $args]==0 } {
                 puts "[info procs [concat $namespace *]]"
         } else {
            "$namespace [lindex $args 0]" {expand}[lrange $args 1 end]
         }
 }

 # do some tests with string
 rename string _string

 proc {string bytelength} {args} {
   _string bytelength {expand}$args
 }

 proc {string compare} {args} {
   _string compare {expand}$args
 }


 proc {string equal} {args} {
   _string equal {expand}$args
 }


 proc {string first} {args} {
   _string first {expand}$args
 }


 proc {string index} {args} {
   _string index {expand}$args
 }


 proc {string is} {args} {
   _string is {expand}$args
 }

 proc {string last} {args} {
   _string last {expand}$args
 }

 proc {string length} {string} {
   _string length $string
 }

 proc {string map} {args} {
   _string map {expand}$args
 }

 proc {string match} {args} {
   _string match {expand}$args
 }

 #range repeat replace tolower toupper totitle trim trimleft trimright wordend wordstart 

 proc {string} {args} {
   # puts "called string $args"
   set namespace [lindex [info level 0] 0]
         if { [llength $args]==0 } {
                 puts "[info procs [concat $namespace *]]"
         } else {
            "$namespace [lindex $args 0]" {expand}[lrange $args 1 end]
         }
 }


 puts [string length 12]

 # show all commands in the win32 namespace
 puts [win32]