Usage:
getopts(options [, init])
getopts() is a function that parses and validates macro options according to the format described by options. Options is a list of letters that getopts() will accept; if a letter is followed by ':', the option will be expected to have a string argument, and if a letter is followed by "#" the option will be expected to have a numeric argument. The option syntax accepted by getopts() is the same as that accepted by builtin tf commands, as described under "options".
When an option is found, getopts() creates a new local variable named "opt_X", where "X" is the letter of the option. If an argument is expected, the variable will get that argument as its value; otherwise, the variable will have a value of "1".
If init is given, the variables corresponding to each letter of options are initialized to init before processing the command line options. If init is omitted, the variables are not initialized, so if variables with the same names already exist and are not set by getopts(), they will be unchanged. You can use this to set the variables to some default value before calling getopts().
The argument list will be shifted to discard the options that have been parsed, so %{*} will contain the remainder of the arguments, without the options.
If getopts() encounters an error, it will print an error message and return 0; otherwise, it returns nonzero.
Using getopts(), /escape, and /split, it is possible to write macros that behave just like builtin tf commands.
Here's a contrived example to illustrate how getopts() works:
/def foo = \ /if (!getopts("abns:", "")) /return 0%; /endif%; \ /echo option a: %{opt_a}%;\ /echo option b: %{opt_b}%;\ /echo option n: %{opt_n}%;\ /echo option s: %{opt_s}%;\ /echo args: %{*}%;\ /split %{*}%;\ /echo name: %{P1}%;\ /echo body: %{P2}
Now, all of these commands are equivalent:
/foo -a -b -n5 -s"can't stop" -- whiz = bang biff /foo -a -b -n5 -s'can\'t stop' whiz = bang biff /foo -n5 -ba -s`can't stop` whiz = bang biff /foo -as"can't stop" -bn5 whiz = bang biffand produce this output:
option a: 1 option b: 1 option n: 5 option s: can't stop args: whiz = bang biff name: whiz body: bang biff
But the command:
/foo -a -x whiz = bang biffproduces the error:
foo: invalid option 'x'
See: expressions, functions, options, /escape, /split