Version 3 of optproc

Updated 2007-09-28 06:53:19 by suchenwi

slebetman: optproc proc allows you to define procs where the syntax for arguments behave like "options". Like what we often see in Tk. After the umpteenth time writing/using argument parsers to do this I thought there ought to be a better, more natural way:

  proc optproc {name args script} {
    proc $name args [
      string map [list ARGS $args SCRIPT $script] {
        foreach var {ARGS} {
          set [lindex $var 0] [lindex $var 1]
        }

        foreach {var val} $args {
          set [string trim $var -] $val
        }

        SCRIPT
      }
    ]
  }

The syntax is similar to proc except that when calling procs defined by optproc the arguments need to be accompanied by their name. Also when calling the created procedure the order of arguments doesn't matter. Default values for arguments are defined just like default values in proc. If no default is defined then the argument's value defaults to an empty string.

Example usage:

  optproc testproc {text {case "upper"}} {
    switch -- $case {
      upper {set text [string toupper $text]}
      lower {set text [string tolower $text]}
    }
    puts $text
  }

  # Calling "testproc":

  testproc -text Hello              ;# this prints out HELLO
  testproc -text Hello -case lower  ;# this prints out hello
  testproc -text Hello -case none   ;# this prints out Hello

RS: Nice - simple and powerful! Note however that such optprocs will not be listed in tclIndex, as auto_mkindex goes only for calls to proc.


[ Category Function ]