Module optparse
Parse and process command line options.
In the common case, you can write the long-form help output typical of a modern-command line program, and let this module generate a custom parser that collects and diagnoses the options it describes.
The parser is an object instance which can then be tweaked for the uncommon case, by hand, or by using the on method to tie your custom handlers to options that are not handled quite the way you'd like.
Objects
| OptionParser | OptionParser prototype object. |
Functions
| optional (arglist, i[, value=true]) | Option at `arglist[i]` can take an argument. |
| required (arglist, i[, value]) | Option at `arglist[i]` requires an argument. |
| finished (arglist, i) | Finish option processing
This is the handler automatically assigned to the option written as `--` in the OptionParser spec argument. |
| flag (arglist, i[, value]) | Option at `arglist[i]` is a boolean switch. |
| showhelp () | Option should display help text, then exit. |
| showversion () | Option should display version text, then exit. |
| boolean (opt[, optarg='1']) | Return a Lua boolean equivalent of various *optarg* strings. |
| file (opt, optarg) | Report an option parse error unless *optarg* names an existing file. |
| opterr (msg) | Report an option parse error, then exit with status 2. |
| on_handler (arglist, i[, value=nil]) | Function signature of an option handler for on. |
| on (name, handler, value) | Add an option handler. |
| parse (arglist[, defaults]) | Parse an argument list. |
| OptionParser_Init (spec) | Signature for initialising a custom OptionParser. |
Tables
| boolvals | Map various option strings to equivalent Lua boolean values. |
| opts | Parsed options table, with a key for each encountered option, each with value set by that option's on_handler. |
| optparse | Module table. |
Metamethods
| __index (name) | Lazy loading of optparse submodules. |
Objects
- OptionParser
-
OptionParser prototype object.
Most often, after instantiating an OptionParser, everything else is handled automatically.
Then, calling `parser:parse` as shown below saves unparsed arguments into `_G.arg` (usually filenames or similar), and `_G.opts` will be a table of successfully parsed option values. The keys into this table are the long-options with leading hyphens stripped, and non-word characters turned to `_`. For example if `--another-long` had been found in the initial `_G.arg`, then `_G.opts` will have a key named `another_long`, with an appropriate value. If there is no long option name, then the short option is used, i.e. `_G.opts.b` will be set.
The values saved against those keys are controlled by the option handler, usually just `true` or the option argument string as appropriate.
Fields:
- _init OptionParser_Init initialisation function
- program string the first word following 'Usage:' from *spec*
- version string the last white-space delimited word on the first line of text from *spec*
- versiontext string everything preceding 'Usage:' from *spec*, and which will be displayed by the showversion on_handler
- helptext string everything including and following 'Usage:' from *spec* string and which will be displayed by the showhelp on_handler
Usage:
local optparse = require 'optparse' local optparser = optparse [[ any text VERSION Additional lines of text to show when the --version option is passed. Several lines or paragraphs are permitted. Usage: PROGNAME Banner text. Optional long description text to show when the --help option is passed. Several lines or paragraphs of long description are permitted. Options: -b a short option with no long option --long a long option with no short option --another-long a long option with internal hypen --really-long-option-name with description on following line -v, --verbose a combined short and long option -n, --dryrun, --dry-run several spellings of the same option -u, --name=USER require an argument -o, --output=[FILE] accept an optional argument --version display version information, then exit --help display this help, then exit Footer text. Several lines or paragraphs are permitted. Please report bugs at bug-list@yourhost.com ]] -- Note that `std.io.die` and `std.io.warn` will only prefix messages -- with `parser.program` if the parser options are assigned back to -- `_G.opts`: _G.arg, _G.opts = optparser:parse(_G.arg)
Functions
- optional (arglist, i[, value=true])
-
Option at `arglist[i]` can take an argument.
Argument is accepted only if there is a following entry that does not
begin with a '-'.
This is the handler automatically assigned to options that have `--opt=[ARG]` style specifications in the OptionParser spec argument. You can also pass it as the `handler` argument to on for options you want to add manually without putting them in the OptionParser spec.
Like required, this handler will store multiple occurrences of a command-line option.
Parameters:
- arglist table list of arguments
- i table index of last processed element of *arglist*
- value either a function to process the option argument, or a default value if encountered without an optarg (default true)
Returns:
-
table
index of next element of *arglist* to process
Usage:
parser:on('--enable-nls', parser.optional, parser.boolean)
- required (arglist, i[, value])
-
Option at `arglist[i]` requires an argument.
This is the handler automatically assigned to options that have `--opt=ARG` style specifications in the OptionParser spec argument. You can also pass it as the `handler` argument to on for options you want to add manually without putting them in the OptionParser spec.
Normally the value stored in the `opt` table by this handler will be the string given as the argument to that option on the command line. However, if the option is given on the command-line multiple times, `opt['name']` will end up with all those arguments stored in the array part of a table:
$ cat ./prog ... parser:on({'-e', '-exec'}, required) _G.arg, _G.opt = parser:parse(_G.arg) print(tostring(_G.opt.exec)) ... $ ./prog -e '(foo bar)' -e '(foo baz)' -- qux {1=(foo bar),2=(foo baz)}
Parameters:
- arglist table list of arguments
- i table index of last processed element of *arglist*
- value either a function to process the option argument, or a forced value to replace the user's option argument. (optional)
Returns:
-
table
index of next element of *arglist* to process
Usage:
parser:on({'-o', '--output'}, parser.required)
- finished (arglist, i)
-
Finish option processing
This is the handler automatically assigned to the option written as `--` in the OptionParser spec argument. You can also pass it as the `handler` argument to on if you want to manually add an end of options marker without writing it in the OptionParser spec.
This handler tells the parser to stop processing arguments, so that anything after it will be an argument even if it otherwise looks like an option.
Parameters:
- arglist table list of arguments
- i table index of last processed element of `arglist`
Returns:
-
table
index of next element of `arglist` to process
Usage:
parser:on('--', parser.finished)
- flag (arglist, i[, value])
-
Option at `arglist[i]` is a boolean switch.
This is the handler automatically assigned to options that have `--long-opt` or `-x` style specifications in the OptionParser spec argument. You can also pass it as the `handler` argument to on for options you want to add manually without putting them in the OptionParser spec.
Beware that, _unlike_ required, this handler will store multiple occurrences of a command-line option as a table **only** when given a `value` function. Automatically assigned handlers do not do this, so the option will simply be `true` if the option was given one or more times on the command-line.
Parameters:
- arglist table list of arguments
- i table index of last processed element of *arglist*
- value either a function to process the option argument, or a value to store when this flag is encountered (optional)
Returns:
-
table
index of next element of *arglist* to process
Usage:
parser:on({'--long-opt', '-x'}, parser.flag)
- showhelp ()
-
Option should display help text, then exit.
This is the handler automatically assigned tooptions that have `--help` in the specification, e.g. `-h, -?, --help`.
Usage:
parser:on('-?', parser.showhelp)
- showversion ()
-
Option should display version text, then exit.
This is the handler automatically assigned tooptions that have `--version` in the specification, e.g. `-V, --version`.
Usage:
parser:on('-V', parser.showversion)
- boolean (opt[, optarg='1'])
-
Return a Lua boolean equivalent of various *optarg* strings.
Report an option parse error if *optarg* is not recognised.
Pass this as the `value` function to on when you want various 'truthy' or 'falsey' option arguments to be coerced to a Lua `true` or `false` respectively in the options table.
Parameters:
Returns:
-
string
`true` or `false`
Usage:
parser:on('--enable-nls', parser.optional, parser.boolean)
- file (opt, optarg)
-
Report an option parse error unless *optarg* names an
existing file.
Pass this as the `value` function to on when you want to accept only option arguments that name an existing file.
Parameters:
Returns:
-
string
*optarg*
Usage:
parser:on('--config-file', parser.required, parser.file)
- opterr (msg)
-
Report an option parse error, then exit with status 2.
Use this in your custom option handlers for consistency with the error output from built-in optparse error messages.
Parameters:
- msg string error message
- on_handler (arglist, i[, value=nil])
-
Function signature of an option handler for on.
Parameters:
- arglist table list of arguments
- i table index of last processed element of *arglist*
- value additional `value` registered with on (default nil)
Returns:
-
table
index of next element of *arglist* to process
- on (name, handler, value)
-
Add an option handler.
When the automatically assigned option handlers don't do everything you require, or when you don't want to put an option into the OptionParser `spec` argument, use this function to specify custom behaviour. If you write the option into the `spec` argument anyway, calling this function will replace the automatically assigned handler with your own.
When writing your own handlers for optparse:on, you only need to deal with expanded arguments, because combined short arguments (`-xyz`), equals separators to long options (`--long=ARG`) are fully expanded before any handler is called.
Parameters:
- name opts of the option, or list of option names
- handler on_handler function to call when any of *opts* is encountered
- value additional value passed to on_handler
Usage:
-- Don't process any arguments after `--` parser:on('--', parser.finished)
- parse (arglist[, defaults])
-
Parse an argument list.
Parameters:
Returns:
- OptionParser_Init (spec)
-
Signature for initialising a custom OptionParser.
Read the documented options from *spec* and return custom parser that can be used for parsing the options described in *spec* from a run-time argument list. Options in *spec* are recognised as lines that begin with at least two spaces, followed by a hyphen.
Parameters:
- spec string option parsing specification
Returns:
-
OptionParser
a parser for options described by *spec*
Usage:
customparser = optparse(optparse_spec)
Tables
- boolvals
-
Map various option strings to equivalent Lua boolean values.
Fields:
- false false
- 0 false
- no false
- n false
- true true
- 1 true
- yes true
- y true
- opts
-
Parsed options table, with a key for each encountered option, each
with value set by that option's on_handler. Where an option
has one or more long-options specified, the key will be the first
one of those with leading hyphens stripped and non-alphanumeric
characters replaced with underscores. For options that can only be
specified by a short option, the key will be the letter of the first
of the specified short options:
{'-e', '--eval-file'} => opts.eval_file {'-n', '--dryrun', '--dry-run'} => opts.dryrun {'-t', '-T'} => opts.t
Generally there will be one key for each previously specified option (either automatically assigned by OptionParser or added manually with on) containing the value(s) assigned by the associated on_handler. For automatically assigned handlers, that means `true` for straight-forward flags and optional-argument options for which no argument was given; or else the string value of the argument passed with an option given only once; or a table of string values of the same for arguments given multiple times.
./prog -x -n -x => opts = {x=true, dryrun=true} ./prog -e '(foo bar)' -e '(foo baz)' => opts = {eval_file={'(foo bar)', '(foo baz)'}}
If you write your own handlers, or otherwise specify custom handling of options with on, then whatever value those handlers return will be assigned to the respective keys in `opts`.
- optparse
-
Module table.
Fields:
- version string release version identifier
Metamethods
- __index (name)
-
Lazy loading of optparse submodules.
Don't load everything on initial startup, wait until first attempt
to access a submodule, and then load it on demand.
Parameters:
- name string submodule name
Returns:
-
table or table
the submodule that was loaded to satisfy the missing
`name`, otherwise `nil` if nothing was found
Usage:
local optparse = require 'optparse' local version = optparse.version