Host variables
$name is a variable set and read by the program that launched the script. In the «Script» block these are the bot's variables (Scripts in bots), in the terminal the -v and --vars flags.
Reading and writing
$nope # → nil
defined($nope) # → false
$count = 1
$count + 1 # → 2
defined($count) # → trueAn unset variable is nil, not an error. So a condition on it is simply false.
if $vip { "discount" } else { "no discount" } # → "no discount"
$name ?? "guest" # → "guest"defined asks whether the variable is set, not what its value is:
$x = nil
defined($x) # → trueA separate namespace
$name has nothing to do with a local variable name and is visible from any function without capturing.
sent = "local"
sent # → "local"
$sent # → nil
fn remember(v) { $last = v }
remember(42)
$last # → 42
[1, 2, 3].each { $sum = ($sum ?? 0) + it }
$sum # → 6Strings on input
Values from -v are always strings and are not converted by themselves:
mzs -v x=5 -e 'type($x)' # string
mzs -v x=5 -e '$x + 1' # type: cannot add int to string
mzs -v x=5 -e '$x.int + 1' # 6.int and .float never fail, so they are safe for an unset variable too:
| Value | .int | .float |
|---|---|---|
"42" | 42 | 42.0 |
"12abc" | 12 | 12.0 |
"abc", "" | 0 | 0.0 |
nil (unset) | 0 | 0.0 |
$visits = $visits.int + 1
$visits # → 1In strings
"$name" inserts a host variable. An expression goes in ${…}:
$price = 1500
"total: $price ₽" # → "total: 1500 ₽"
"discounted: ${$price * 0.9} ₽" # → "discounted: 1350.0 ₽"The name is taken as long as possible: "$n00" is the variable $n00. To end the name, write "${$n}00".
Command-line flags
| Flag | What it does |
|---|---|
-v k=v | $k = the string v; can be repeated |
--vars '<json>' | each field of a JSON object, with JSON types |
--vars-file path | the same from a file |
mzs -v a=1 -v b=2 -e '[$a, $b]' --json
# ["1","2"]
mzs --vars '{"x":5,"tags":["a"],"ok":true}' -e '[type($x), type($tags), type($ok)]' --json
# ["int","array","bool"]
mzs -v price=1500 -e '"total: ${$price.int + 100}"'
# total: 1600Line mode
With -n the script runs for each input line, the line is in $_. Host variables persist between lines:
printf 'a\nbb\n' | mzs -n -e '$n = ($n ?? 0) + 1; "${$n}:${$_}"'
# 1:a
# 2:bb