Zig
Write a Basalt plugin in Zig: tiny modules, no hidden allocation and the Zig standard library where it makes sense.
Choose Zig when you want C-sized modules and C-like speed with a modern language: slices instead of pointers, optionals
instead of sentinel values and comptime where you need it. A greeter is about 2 KB. Nothing allocates unless you ask: the
SDK works over buffers you own, and the standard library is there when you want formatting or an allocator. The cost is
that Zig changes between releases, and that you manage the buffers yourself in the same way as in C.
What Kiln installs#
Nothing by hand. Kiln uses a zig on your PATH from version 0.14, and otherwise downloads Zig 0.17.1 (about 55 MB,
407 MB unpacked) into a per-user cache on the first build, on Linux, macOS and Windows. The language moves between
releases, so the pinned version is the one the SDK is built against. See Kiln.
Project layout#
kiln new greeter --lang ziggreeter/
plugin.toml
.gitignore
resources/config.toml
resources/lang/en_us.toml
src/main.zigsrc/main.zig is the root of your plugin. Other files are ordinary Zig files that you @import from it. The module is
written to build/plugin.wasm; build/.kiln/ holds the SDK copy and scratch files and is rebuilt each time.
The entry point#
Write pub fn init() void in src/main.zig. Kiln generates a small root file that exports what the server needs and calls
your init once, after the module loads; that is where you register listeners, commands and tasks.
A first plugin#
This plugin greets a player when they join and adds a /greeter hello [times] command. It is the whole of src/main.zig.
const basalt = @import("basalt_server");
fn onJoin(ctx: basalt.core.Ctx) void {
const player = basalt.events.playerOf(ctx);
if (player == 0) return;
var name: [64]u8 = undefined;
var args = basalt.core.Args.init();
_ = args.add("name", basalt.players.name(player, &name) orelse "player");
_ = basalt.players.send(player, "<green>Welcome, {name}!", &args);
}
fn hello(ctx: basalt.core.Ctx) void {
const times = basalt.commands.argI64(ctx, "times") orelse 1;
var i: i64 = 0;
while (i < times) : (i += 1) {
_ = basalt.commands.reply(ctx, "<yellow>Hello from greeter!", null);
}
}
pub fn init() void {
basalt.log.info("greeter loaded");
_ = basalt.events.on("player.join", basalt.core.Priority.normal, onJoin);
_ = basalt.commands.register("greeter hello [times: int 1..5]", "", hello);
}events.on listens to an event, see Events; commands.register registers a command from a
spec such as greeter hello [times: int 1..5], see Commands. The text is
MiniMessage, and {name} is filled from the arguments.
How the SDK names things#
Pages in this section write calls in the C++ form (players::send); the Zig spelling is in The SDK.
- Where things live:
const basalt = @import("basalt_server");gives one namespace per area,basalt.players,basalt.events,basalt.values, and so on. Functions are camelCase and some drop the area name:players::player_nameisplayers.name,events::event_playerisevents.playerOf,commands::command_arg_i64iscommands.argI64,config::config_i64isconfig.getI64. - Strings in are slices,
[]const u8, so a string literal works directly. - Strings out go into a
[]u8buffer you pass, and the call gives back?[]const u8, a slice of that buffer, ornullon failure. - Optional arguments are optionals: pass
null, or&args, for?*const core.Args. - Handles are
core.Playerandcore.Ctx, bothi32.0is never a valid handle. Argsiscore.Args:Args.init(), thenadd(key, value), which returns theArgsso pairs chain. It holds 1024 bytes in total, and a pair that does not fit is dropped.- Constants are
core.Priority.lowesttocore.Priority.highest,core.Levelandcore.Statusfor the result codes. - Results: a call that only does something returns an
i32status. Zig does not let you ignore a value, so write_ = basalt.players.send(...)when you do not check it. - Numbers to text:
core.formatI64(value, &buf), orstd.fmt.bufPrintfrom the standard library. - Handlers are function values,
*const fn (ctx: core.Ctx) void. They cannot capture variables, so keep state in file-levelvars.
Working with values#
Structured data is a value, see Values. values.Writer.init(buffer) writes into a buffer
you own (Writer.initAlloc(allocator) grows one instead), and a call that returns a value gives you
Error!values.Value, which you read in place. This keeps a count of joins in a JSON document (it needs the storage
capability, see
Configuration and storage):
fn recordJoin(who: []const u8) void {
var reply: [1024]u8 = undefined;
var total: i64 = 0;
if (basalt.server.dataRead("joins", &reply)) |doc| {
if (doc.find("total")) |value| total = value.asInt() orelse 0;
} else |_| {}
var out: [256]u8 = undefined;
var writer = basalt.values.Writer.init(&out);
writer.beginMap();
writer.key("total");
writer.int(total + 1);
writer.key("last");
writer.string(who);
writer.end();
const document = writer.finish() catch return;
_ = basalt.server.dataWrite("joins", document);
}The writer has nullValue, boolean, int, float, string, bytes, beginList, beginMap, end and key, and
finish() returns the document or error.Invalid or error.Overflow. For reading, find (a map), at (a list),
count and items() walk a document, and asInt, asFloat, asBool, asString and asBytes return an optional that
is null when the value has another kind. Errors from calls are error.Absent, Stale, Invalid, Denied, Failed
and TooLarge, matching the result codes. The slice a getter returns
points into your buffer, so keep the buffer alive while you read.
Building#
kiln buildcompiles for wasm32-freestanding in ReleaseSmall and writes build/plugin.wasm, then checks it. The plugin above is
about 2.1 KB and builds in a fraction of a second. kiln pack writes build/greeter-0.1.0.bspkg for the server's
plugins/ folder, see Kiln.
Proxy plugins#
The same language writes proxy plugins: kiln new <id> --lang zig --target proxy, with @import("basalt_proxy") in place
of @import("basalt_server"). Proxy plugins are packed as .bppkg, see Proxy plugins.
Things to know#
ReleaseSmallturns the safety checks off. An out-of-range slice index or an integer overflow is not caught and stopped as it would be in a safe build, so check indexes and sizes yourself.- The standard library works where it needs no operating system.
std.fmt,std.mem, the containers andstd.heap.wasm_allocatorare available. There are no files, threads, sockets or clock, because there is no OS under the module. - No allocator by default. The SDK never allocates. If you want heap memory, take
std.heap.wasm_allocator; it reuses memory you free, but the module's memory never shrinks. - At most 1024 callbacks. Each listener, command, task and menu slot you register takes one entry for the life of the
module. Registering beyond that returns
Status.invalid. - Your buffer must hold the answer. Calls that return a value fail with
error.TooLargewhen the answer does not fit the buffer you pass, so size it for the biggest answer you expect. Documents can be up to 1 MiB. players.onlinefills nothing when the array is too small. Size the array above the number of players you expect online, and treat a result equal to the array length as possibly cut off.- A trap disables the plugin, not the server.
unreachable,@panicand a division by zero stop the callback and count as a failure, see Execution model.
Where to go next#
| The SDK | How calls, handles and errors work in every language |
| Values | The structured data format in full |
| Kiln | Creating, building and packing |
| Performance | Measured numbers and how to keep a tick short |
The same greeter, a leaderboard and a shop are a full example in the
ServerPlugin-Example repository, on the branch zig.