Skip to content

Modules and Imports

Zap’s module system is file-based. Each .zp file is a module. You import other modules by path, and control what’s visible outside with pub.

import "math";

After this, access exported symbols through the module name:

import "math";
fun main() Int {
var v: math.Vec2 = math.Vec2{ x: 3, y: 4 };
var len: Int = math.lengthSquared(v);
return 0;
}

Import only specific symbols to use them without the module prefix:

import "std/io" { println, printInt };
fun main() Int {
println("Hello!");
printInt(42);
return 0;
}

Give a module a shorter name with as:

import "std/io" as io;
import "std/string" as str;
fun main() Int {
io.println("Hello!");
var n: Int = str.len("Zap");
return 0;
}

By default, symbols in a module are private. Mark them pub to make them importable:

math.zp
pub alias Score = Int;
pub struct Vec2 {
x: Int,
y: Int,
}
pub fun lengthSquared(v: Vec2) Score {
return v.x * v.x + v.y * v.y;
}
pub fun dot(a: Vec2, b: Vec2) Int {
return a.x * b.x + a.y * b.y;
}
// This function is NOT exported (no pub):
fun helper() Int { return 0; }

math.zp:

pub struct Vec2 {
x: Int,
y: Int,
}
pub fun lengthSquared(v: Vec2) Int {
return v.x * v.x + v.y * v.y;
}
pub fun dot(a: Vec2, b: Vec2) Int {
return a.x * b.x + a.y * b.y;
}

app.zp:

import "math";
import "std/io" { printInt };
fun main() Int {
var a: math.Vec2 = math.Vec2{ x: 3, y: 4 };
var b: math.Vec2 = math.Vec2{ x: 2, y: 5 };
printInt(math.lengthSquared(a)); // 25
printInt(math.dot(a, b)); // 26
return 0;
}

Compile with:

Terminal window
zapc app.zp -o app

Importing a directory loads all .zp files in that directory as a single module namespace:

import "utils"; // loads utils/helpers.zp, utils/math.zp, etc.

This is useful for organizing larger modules into multiple files.


ModuleWhat it provides
std/ioConsole I/O: println, printInt, getLn, printf, printfln, …
std/stringString operations: len, at, slice, eq, fromChar, pushChar
std/fsFile system: readFile, writeFile, mkdirAll
std/pathPath manipulation: join, basename, parent
std/mathMath functions: sqrt, abs, pow, floor, ceil, …
std/convertType conversions: intToString, floatToInt, stringToInt, …
std/memManual memory: malloc, free (requires --allow-unsafe)
std/processProcess info: argc, argv, cwd, exit
std/errorError utilities and types
std/preludeSymbols available everywhere without import (println, printInt, …)

→ See the Standard Library section for full API documentation.


CodeMeaning
S2001Undefined symbol — imported name doesn’t exist in the module
P1003Unexpected token in import statement