Version 6 of optproc

Updated 2007-10-05 04:54:49 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.

slebetman Hmm. The man page for auto_mkindex states that it parses files by sourcing them into a slave interp. Which means that optprocs should be listed since it is merely a wrapper around proc (as info procs would show).

RS "Calculemus!" as Leibniz said - Tcl 8.4.5, Win 95:

 /_Ricci/tmp> cat t.tcl
 proc optproc {name argl body} {proc $name $argl $body}
 interp alias {} _proc {} proc
 optproc f x {set x}
 _proc g x {set x}

 /_Ricci/tmp> echo auto_mkindex . | tclsh
 /_Ricci/tmp> cat tclIndex
 # Tcl autoload index file, version 2.0
 # This file is generated by the "auto_mkindex" command
 # and sourced to set up indexing information for one or
 # more commands.  Typically each line is a command that
 # sets an element in the auto_index array, where the
 # element name is the name of a command and the value is
 # a script that loads the command.

 set auto_index(optproc) [list source [file join $dir t.tcl]]
 /_Ricci/tmp>

So neither optproc nor the interp alias _proc which I usually use to hide procs from indexing are executed, and hence rerouted to proc; and so neither f nor g end up in the tclIndex. Looks like the interpreter skips commands not in core Tcl...


[ Category Function ]