Skip to content

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 ​

mzs
$nope  # → nil
defined($nope)  # → false

$count = 1
$count + 1  # → 2
defined($count)  # → true

An unset variable is nil, not an error. So a condition on it is simply false.

mzs
if $vip { "discount" } else { "no discount" }  # → "no discount"
$name ?? "guest"  # → "guest"

defined asks whether the variable is set, not what its value is:

mzs
$x = nil
defined($x)  # → true

A separate namespace ​

$name has nothing to do with a local variable name and is visible from any function without capturing.

mzs
sent = "local"
sent  # → "local"
$sent  # → nil

fn remember(v) { $last = v }
remember(42)
$last  # → 42

[1, 2, 3].each { $sum = ($sum ?? 0) + it }
$sum  # → 6

Strings on input ​

Values from -v are always strings and are not converted by themselves:

sh
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"4242.0
"12abc"1212.0
"abc", ""00.0
nil (unset)00.0
mzs
$visits = $visits.int + 1
$visits  # → 1

In strings ​

"$name" inserts a host variable. An expression goes in ${…}:

mzs
$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 ​

FlagWhat 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 paththe same from a file
sh
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: 1600

Line mode ​

With -n the script runs for each input line, the line is in $_. Host variables persist between lines:

sh
printf 'a\nbb\n' | mzs -n -e '$n = ($n ?? 0) + 1; "${$n}:${$_}"'
# 1:a
# 2:bb