ns_parseargs - Parse list of arguments
This function parses a list of arguments against an argument specification and stores the resulting bindings in local Tcl variables.
argspec argument specifications, which is a list of specifications for single positional or non-positional arguments. When an argument spec starts with a "-", it specifies a non-positional argument. When an argument spec consists of two values, the latter one is a default. The special argument spec "--" (two dashes) denotes a potential end of the block of non-positional arguments
arguments List of arguments to be parsed
The first example shows the practical usage of ns_parseargs in a proc. The intention is to define a proc "ns_getcontent" which might be called with the optional arguments -as_file or -binary. The default value for both of these arguments is true. To achieve this, the proc "ns_getcontent" is defined with the argument spec args, which allows all kinds of arguments to be passed. As a fist call, it invokes the argument parser with the detailed argument spec. In case, the arguments can't be parsed according to the spec, "ns_parseargs" raises an error.
# # Define a function with two positional arguments # proc ns_getcontent {args} { ns_parseargs { {-as_file true} {-binary true} } $args if {![string is boolean -strict $as_file]} { return -code error "value of '$as_file' is not boolean" } if {![string is boolean -strict $binary]} { return -code error "value of '$binary' is not boolean" } # ... }
The second example demonstrates non-positional and positional arguments with and without defaults.
% ns_parseargs {-a {-b 1} -- c {d x}} {-- 1 } % lappend _ [info exists a] [info exists b] [info exists c] [info exists d] 0 1 1 1