mod — Defining Modules
The mod keyword is used to define modules in Nitpick, allowing you to organize your code into hierarchical namespaces and control visibility.
Inline Modules
You can define a module directly in the current file using an inline block:
mod network {
pub func:connect = int32() {
pass 0i32;
};
// Private by default
func:internal_setup = int32() {
pass 0i32;
};
}
func:main = int32() {
int32:res = raw network.connect();
exit res;
};
External File Modules
Instead of writing the entire module inline, you can move it to a separate file:
// main.npk
mod network;
func:main = int32() {
int32:res = raw network.connect();
exit res;
};
File Lookup Convention
When the compiler sees mod network;, it searches for the implementation in the following locations relative to the declaring file:
1. network.npk
2. network/mod.npk
// network.npk (Implementation of the 'network' module)
pub func:connect = int32() {
pass 0i32;
};
Nested Modules
Modules can be nested arbitrarily deep, allowing for robust categorization of functionality.
mod core {
pub mod math {
pub func:add = int32(int32:a, int32:b) {
pass (a + b);
};
}
}
func:main = int32() {
int32:res = raw core.math.add(1i32, 2i32);
exit res;
};
Visibility (pub mod)
By default, modules are private to the scope in which they are declared. To allow outer scopes to access a nested module and its public contents, use pub mod:
mod core {
pub mod public_utils {
pub func:help = int32() { pass 0i32; };
}
mod private_utils {
pub func:help = int32() { pass 0i32; };
}
}
func:main = int32() {
raw core.public_utils.help(); // OK
// raw core.private_utils.help(); // Error: module is private
exit 0;
};
Qualified Access
Symbols defined within a module (whether inline or external) can be accessed using dot notation: ModuleName.SymbolName.
Related
- use_import.md — importing modules
- visibility.md — public vs private symbols