Skip to content

args — command-line flags ​

mzs
include args

WARNING

Not available in bot scripts: a bot script has no command line.

FunctionWhat it does
args.parse(spec, opts = {})$ARGV → a dict: each flag under its key from spec, plus rest for the positional ones
args.usage(spec, opts = {})the help text, the same one --help prints

Everything after the script path is the script's arguments: mzs resize.mzs --width 640 photo.png.

Describing flags ​

The key is the flag (dry_run → --dry-run); the value is a dict or just the default value.

KeyMeaning
defaultthe value without the flag; its type sets the conversion
helpa line for the help text
shortone letter: short: "q" → -q
requiredtrue: the flag is mandatory
DefaultOn the command lineValue
false / true--force, --no-forcebool
int--width 800, --width=800int
float--quality 0.5float
a string or nil--out xa string
[]--tag a --tag ban array of strings
OptionWhat it does
usagethe line after usage: in the help text
min, maxhow many positional arguments are allowed
argvparse this array instead of $ARGV
exitfalse: raise an error instead of exiting

Parse ​

mzs
include args
spec = {
  width: {default: 800, help: "width in pixels"},
  quality: {default: 0.85, short: "q"},
  force: {default: false, short: "f"},
  tag: [],
}
args.parse(spec)  # → {"width":800,"quality":0.85,"force":false,"tag":[],"rest":[]}
args.parse(spec, {argv: ["--width", "640", "-fq", "0.5", "--tag", "web", "--tag", "hero", "photo.png"]})  # → {"width":640,"quality":0.5,"force":true,"tag":["web","hero"],"rest":["photo.png"]}
args.parse({dry_run: true}, {argv: ["--no-dry-run"]})  # → {"dry_run":false,"rest":[]}
  • Short bools combine: -fv; the last one may take a value: -fq 0.5.
  • -- ends the flags.
  • A repeated flag keeps the last value; an array keeps all.

Help ​

-h and --help always exist: they print the help and end the script with code 0.

mzs
include args
print(args.usage({width: {default: 800, help: "width in pixels"}, force: {default: false, short: "f"}}, {usage: "resize [flags] <file>…"}))
text
usage: resize [flags] <file>…

flags:
  -h, --help         show this help
      --width <int>  width in pixels (default 800)
  -f, --force

Errors ​

An unknown flag, a bad value, too few arguments: a message and the help go to stderr, exit code 2.

sh
$ mzs resize.mzs --widht 640 photo.png
resize: unknown flag --widht (did you mean --width?)

With exit: false: an argument error with {flag, reason} in data; that is how tests check the parsing.

mzs
include args
spec = {width: 800, quality: 0.85}
try args.parse(spec, {argv: ["--quality", "fast"], exit: false}) else (e) -> e["data"]  # → {"flag":"--quality","reason":"bad_value"}
try args.parse(spec, {argv: ["--widht", "9"], exit: false}) else (e) -> e["data"]["reason"]  # → "unknown"
try args.parse(spec, {argv: [], exit: false, min: 1}) else (e) -> e["data"]["reason"]  # → "too_few"