Class std.optparse

Parse and process command line options.

Prototype Chain ---------------

table `-> Object `-> OptionParser

Objects

std.optparse.OptionParser OptionParser prototype object.

Functions

std.optparse.OptionParser_Init (spec) Signature for initialising a custom OptionParser.
std.optparse.boolean (opt[, optarg="1"]) Return a Lua boolean equivalent of various *optarg* strings.
std.optparse.file (opt, optarg) Report an option parse error unless *optarg* names an existing file.
std.optparse.finished (arglist, i) Finish option processing

This is the handler automatically assigned to the option written as `--` in the std.optparse.OptionParser spec argument.

std.optparse.flag (arglist, i[, value]) Option at `arglist[i]` is a boolean switch.
std.optparse.help () Option should display help text, then exit.
std.optparse.opterr (msg) Report an option parse error, then exit with status 2.
std.optparse.optional (arglist, i[, value=true]) Option at `arglist[i]` can take an argument.
std.optparse.required (arglist, i[, value]) Option at `arglist[i}` requires an argument.
std.optparse.version () Option should display version text, then exit.

Tables

std.optparse.boolvals Map various option strings to equivalent Lua boolean values.
std.optparse.opts Parsed options table, with a key for each encountered option, each with value set by that option's on_handler.

Methods

std.optparse:on (name, handler, value) Add an option handler.
std.optparse:on_handler (arglist, i[, value=nil]) Function signature of an option handler for on.
std.optparse:parse (arglist[, defaults]) Parse an argument list.


Objects

std.optparse.OptionParser
OptionParser prototype object.

Most often, after instantiating an std.optparse.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:

Usage:

    local std = require "std"
    
    local optparser = std.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
      -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

Methods
std.optparse.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:

    std.optparse.OptionParser a parser for options described by *spec*

Usage:

    customparser = std.optparse (optparse_spec)
std.optparse.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)
std.optparse.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:

  • opt string option name
  • optarg string option argument, must be an existing file

Returns:

    string *optarg*

Usage:

    parser:on ("--config-file", parser.required, parser.file)
std.optparse.finished (arglist, i)
Finish option processing

This is the handler automatically assigned to the option written as `--` in the std.optparse.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 std.optparse.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)
std.optparse.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 std.optparse.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 std.optparse.OptionParser spec.

Beware that, _unlike_ std.optparse.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)
std.optparse.help ()
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.version)
std.optparse.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 std.optparse error messages.

Parameters:

std.optparse.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 std.optparse.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 std.optparse.OptionParser spec.

Like std.optparse.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.option, parser.boolean)
std.optparse.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 std.optparse.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 std.optparse.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 std.string.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)
std.optparse.version ()
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.version)

Tables

std.optparse.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
std.optparse.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 std.optparse.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`.

Methods

std.optparse: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 std.optparse.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 std.optparse:on, you only need to deal with normalised arguments, because combined short arguments (`-xyz`), equals separators to long options (`--long=ARG`) are fully expanded before any handler is called.

Parameters:

Usage:

    -- Don't process any arguments after `--`
    parser:on ('--', parser.finished)
std.optparse: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
std.optparse:parse (arglist[, defaults])
Parse an argument list.

Parameters:

  • arglist table list of arguments
  • defaults table table of default option values (optional)

Returns:

  1. table a list of unrecognised *arglist* elements
  2. std.optparse.opts parsing results
generated by LDoc 1.5.0 Last updated 2026-07-25 13:31:42