Your own modules
A module is an ordinary .mzs file. Only what is marked export is visible outside.
export
# money.mzs
export currency = "RUB"
rate = 100 # not exported
export fn from_rubles(r) { r * rate }
fn format(cents) { "${cents / rate}.${(cents % rate).str.rjust(2, "0")} ${currency}" }
export format| Code | What it exports |
|---|---|
export x = 1 | a variable |
export fn f() { … } | a function |
export async fn f() { … } | an async function |
export record Money(…) | a record |
export name | a name already declared |
Exporting a name that does not exist is a compile error of the module.
include … from
# main.mzs
include money from "./money.mzs"
println(money.keys.json)
println(money.format(money.from_rubles(15)))
println(money.currency)
println(defined(money.rate))["currency","from_rubles","format"]
15.00 RUB
RUB
falseA module is a dict of its exports: money.keys, money.has("format"), money["format"] work as on a dict. money.f(x) calls the module's function, money["f"] returns the function itself.
Accessing a name that is not exported is an error of kind name:
include money from "./money.mzs"
try money.rate else (e) -> e["message"] # → "undefined member 'rate' in module 'money'"Records from a module
The constructor is called through the module name; fields work as usual.
include money from "./money.mzs" # in money.mzs: export record Money(amount, currency = "RUB")
m = money.Money(1500)
m.amount += 10
type(m) # → "Money"
match m { money.Money {amount} -> "${amount} ₽"; else -> "?" } # → "1510 ₽"Paths
| Path | Where it is looked up |
|---|---|
"./cart.mzs", "../shared/log.mzs" | next to the file that includes it |
"money" | a library: money.mzs or money/main.mzs in $MZSPATH |
"shop/cart" | a library: shop/cart.mzs in $MZSPATH |
Absolute paths are forbidden, and you cannot leave your own directory with ...
| Error | Why |
|---|---|
a library name carries no .mzs | a library is named without .mzs: "money" or "./money.mzs" |
no such library: looked for … in … | the library is in none of the $MZSPATH directories |
include cycle: a.mzs -> b.mzs -> a.mzs | modules include each other in a circle |
MZSPATH
Library directories, separated by :. The default is ~/.mzs/lib. A MZSPATH you set replaces the default rather than adding to it.
MZSPATH=/opt/team/mzs mzs report.mzs
MZSPATH=/opt/team/mzs:$HOME/.mzs/lib mzs report.mzs # both directories, in order
MZSPATH=vendor mzs report.mzs # relative to the working directoryThe first directory where the name is found wins.
How a module runs
- A module runs once per run, even if several files include it.
- It has its own local variables, but shares
$variables, time and limits. - The same file run directly is an ordinary program:
exportchanges nothing.
Built-in modules
Without from it is a bundled module: include json, include tasks, include http. The list is in Modules.
include json
json.parse('{"a": [1, 2]}')["a"] # → [1,2]