Version 0 of init

Updated 2004-02-11 19:59:29

if 0 { This page supercedes getparams. It is the latest and most elegant version of my named parameter parsing routine. It takes a list of parameters and default values. First it initializes the variables in the parameter list to their given defaults in the calling scope, then it parses the args argument (also in the calling scope) to pick out "-var val" pairs and set them properly. In essence, it declares all your local variables and then allows them to be set by command-line switches.

 }

 proc init { args } {
   upvar args arglist
   if ![ info exists arglist] { upvar argv arglist }

   set rest ""
   if { [ llength $arglist ] == 0 } return
   if { [ llength $arglist ] == 1 } { eval set arglist $arglist }
   set varlist {}
   foreach { var val } $args {
     uplevel 1 set $var \{$val\}
     lappend varlist $var
   }
   foreach { var val } $arglist {
     set var [ string range $var 1 end ]
     if { [ lsearch $varlist $var ] != -1 } {
       uplevel 1 set $var \{$val\}
     } else {
       lappend rest -$var $val
     }
   }
   return $rest
 }

 if 0 {

Examples:

 proc foo { args } {
   init a 1 b 2 c 3
   puts "$a, $b, $c"
 }

 foo -a 3

prints "3, 2, 3"

 foo -b 1 -c 4

prints "1, 1, 4"

One bit of cleverness: if the calling scope _has_ no "args" var, init will use argv instead. Thus if called from the global scope, it will parse your command line for you.

You can also brace arguments:

  foo {
    -a 5
    -b 2
  }

is also valid.

}