Expand description
Command-line argument parsing from a spec table — std.argparse.
local argparse = std.argparse
local spec = {
name = "cardbox",
flags = {
json = { type = "boolean", short = "j", help = "print JSON" },
port = { type = "integer", default = 8080 },
include = { type = "string", multiple = true, short = "I" },
},
positionals = {
{ name = "command", required = true },
{ name = "files", rest = true },
},
}
local r = argparse.parse(arg, spec)
-- r.opts.json true / false / nil
-- r.opts.port 8080 unless --port was given
-- r.opts.include { "a", "b" } for -I a -I b (empty table when absent)
-- r.args.command "list"
-- r.args.files { "x.md", "y.md" }
print(argparse.usage(spec))The spec is data, so a host-specific convention (a --json every
command accepts, say) is one entry in the host’s spec rather than a
feature of this module.
§Accepted forms
--name value,--name=value,-n value,-nvalue- booleans:
--flag,--no-flag,-f; bundled shorts-vqwhen every letter is a boolean flag;--flag=true|falsealso works --some-nameand--some_nameboth address the flagsome_name--ends option parsing; everything after it is positional- a value that starts with
-is only taken for aninteger/numberflag when it parses as one (--offset -3); a string flag given--name --otherraises instead of swallowing the next option
§Results
parse returns { opts, args, rest }. opts holds every flag by
name: the parsed value, the default when absent, {} for an absent
multiple flag, and nil otherwise (so if r.opts.verbose then reads
naturally). args holds the declared positionals by name, the rest
positional as a list. rest is what the spec did not claim — unknown
options and surplus positionals — and is only ever non-empty when
allow_unknown = true; without it those raise.
§Errors
Everything raises, with an argparse: prefix: an unknown option, a
value of the wrong type, a missing required flag or positional, a
surplus positional, and a malformed spec (unknown type, a short
that is not one character, two flags sharing a short, rest on a
positional that is not last, required together with default).
§Not covered
Subcommands (parse the first positional and dispatch to a second
spec), environment-variable fallbacks, and an automatic --help
(declare a boolean flag and print usage(spec) yourself).