Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Introduction

If you have ever tried to call Zig code from Lua, you know the pattern. You push arguments onto the Lua stack, call a function, pop results back. Every new function means writing the same push and pop dance again. Change a struct and you chase down every push and pop that touches it. It turns your binding layer into write-only code: you write it once, and from that point on you dread touching it because any change means fixing all the glue code. It is like writing everything twice.

zua generates that glue code at compile time. You write ordinary Zig functions and types, pass them to Lua, and zua handles the stack for you. Change a struct field, the push and pop logic updates with it. Add a new function, the encode and decode paths are generated from the type itself. No registration calls, no runtime reflection, no stack bookkeeping outside of a few specific cases.

What this book does

The book follows three real projects from an empty Zig file to a complete Lua API. Each project lives in its own part. You pick the project closest to what you are building and follow that part. Concepts are introduced only when the project needs them, explained through the decision that made them necessary. Each chapter adds one piece and you see the whole thing grow.

I wanted something like Crafting Interpreters for zua. I know I am not even near to be mentioned in the same phrase as that book, but I love how it teaches by building. That is what I am trying to do here. Follow its shadow.

The three projects

vecmath

A Lua math library distributed as a shared library that Lua loads with require("vecmath"). You write Vec2 and Vec3 as plain Zig structs and expose them as Lua tables with methods, operator overloads, iteration, and editor stubs. This project stays almost entirely in the table strategy, mostly for didactic purposes.

app-config

A Zig program that owns the Lua VM and runs a user script to configure a mock HTTP server. You decode config tables with optional fields and flexible address formats, store Lua callbacks as route handlers and middleware, manage memory with __gc, and build a stateful middleware chain using closures.

process-inspector

A REPL-driven tool that exposes process lists, memory regions, and scan entries as typed Lua objects. You filter results, write back to memory, and get autocompletion in the shell. Lua is the frontend, Zig is the backend.

What we are building

We are building a vector library for Lua. It will be modest but expressive enough to be useful under certain contexts. I am keeping the surface small: addition, subtraction, scalar multiplication, equality, length, dot product, cross product, normalization, and linear interpolation. Plus a simple 3x3 transform system with identity, rotation, scale, and apply.

Just vectors and transforms, enough to move things around in 2D and 3D space. Quaternions, matrix4x4, SVD decomposition, GPU integration are out of scope, but they would follow the same pattern. If you want to expand this into a full-featured math library, that would be incredible.

Note

I chose a vector library because the idea is to build something that looks like a native Lua value. Vectors let us talk about operators, methods, and plain data in a natural way without the examples feeling artificial.

The API we are working toward looks like this:

local vm = require("vecmath")

local a = vm.vec2(3, 4)
local b = vm.vec2(1, 2)

print(a:length())
print(a:dot(b))
print(a:normalize())

local c = a + b
local d = a - b
local e = a * 2
print(a == vm.vec2(3, 4))

local mid = vm.lerp(a, b, 0.5)

local u = vm.vec3(1, 0, 0)
local v = vm.vec3(0, 1, 0)
print(u:cross(v))
print(u:dot(v))
print(u:length())

local w = u + v

local t = vm.rotate(vm.scale(vm.identity(), 2), math.pi / 4)
local rotated = vm.apply(t, a)
OperationWhat it does
vm.vec2(x, y)Creates a 2D vector
vm.vec3(x, y, z)Creates a 3D vector
a + bComponent-wise addition
a - bComponent-wise subtraction
a * nScalar multiplication
a == bEquality check
a:length()Euclidean norm
a:dot(b)Dot product
a:cross(b)Cross product (vec3 only)
a:normalize()Unit vector
vm.lerp(a, b, t)Linear interpolation
vm.identity()3x3 identity matrix
vm.rotate(t, angle)Rotation around Z
vm.scale(t, factor)Uniform scale
vm.apply(t, v)Transform a vector

But before we get there we first need to set up our Zig project to produce the dylib we will run from our Lua interpreter.

Note

A dylib (dynamic library) is a file with executable code that is not executable by itself. The Lua interpreter can load not only Lua files but also dylibs. When someone writes require("module_name"), Lua first looks for a module_name.lua file. If it does not find one, it searches the working directory for a module_name.so (or .dll on Windows) and then searches the paths configured in package.cpath. You must place your library either in the working directory or in a directory listed in the path.

Setting up the project

The first step is to set up our project. This is a Zig library, so we need a Zig project.

Create a directory for the project:

mkdir -p ~/coding/vecmath
cd ~/coding/vecmath

You can use whatever folder you want here. You can also skip this step if you are adding zua to an existing project.

Then initialize the project:

zig init --name vecmath

This generates four files: build.zig, build.zig.zon, src/main.zig, and src/root.zig.

Now we need to add zua as a dependency. Run this from the project root:

zig fetch --save git+https://github.com/SolracHQ/zua

This adds zua to the dependencies section of build.zig.zon.

Next we need to modify build.zig. By default it produces an executable, but we need a dynamic library that Lua can load with require.

Note

If this is your first time with build.zig, do not worry. It looks like a big file but most of it is just comments. Zig’s build system is pretty simple once you get used to it.

Remove the executable section and replace it with a library:

const std = @import("std");

pub fn build(b: *std.Build) void {
    const target = b.standardTargetOptions(.{});
    const optimize = b.standardOptimizeOption(.{});

    const zua_dep = b.dependency("zua", .{
        .target = target,
        .optimize = optimize,
    });

    const lib = b.addLibrary(.{
        .name = "vecmath",
        .linkage = .dynamic,
        .root_module = b.createModule(.{
            .root_source_file = b.path("src/main.zig"),
            .target = target,
            .optimize = optimize,
            .imports = &.{
                .{ .name = "zua", .module = zua_dep.module("zua") },
            },
        }),
    });
    lib.root_module.link_libc = true;
    b.installArtifact(lib);
}

Note

The .name field in addLibrary determines the output file name. On Linux this produces libvecmath.so. Lua expects vecmath.so (without the lib prefix). You can either rename the file after building, or add ;./lib?.so to package.cpath in your test scripts.

Now write the entry point in src/main.zig:

const std = @import("std");
const zua = @import("zua");
const lua = zua.Bindings.lua;

export fn luaopen_vecmath(L: *lua.State) c_int {
    var threaded = std.Io.Threaded.init(std.heap.c_allocator, .{});
    const io = threaded.io();

    const state = zua.State.libState(L, std.heap.c_allocator, io, "vecmath") catch return 0;
    var ctx = zua.Context.init(state);
    defer ctx.deinit();
    zua.Mapper.Encoder.push(&ctx, "Hello Lua") catch return 0;
    return 1;
}

What is happening here? Let us go line by line.

First we initialize the Zig IO interface. This is important because the zua state holds it for any IO access (file access, console access, threading, async, random). It goes alongside the allocator, a familiar pattern in Zig.

Then we initialize the zua state with State.libState. This attaches zua to an existing Lua state instead of creating a new one. The "vecmath" suffix distinguishes this state from other zua-based libraries that might be loaded in the same Lua process. If the same suffix is used again, it returns the existing state instead of allocating a new one. This makes multiple require calls for the same library safe.

Note

Use the name of your library as the state suffix. Since require("name") only loads a module once per Lua state, that name is effectively unique. But there is a deeper reason: the state holds the mapping from Zig type to metatable. If two libraries use the same type name, there will be a silent collision. One metatable gets attached to the wrong type, values get cast to the wrong type, and bad things happen :3.

Now we initialize the Context. The context is required everywhere in the zua API. Do not worry about it too much for now. This is the only one you will write by hand in this project. Inside callback functions, zua provides it automatically. Pin it in your head, it will save us later. For now, it just holds the error message in case push fails (even if pushing a string can never really fail).

Finally we return 1, telling Lua that we pushed one return value.

Now build it:

zig build

This produces zig-out/lib/libvecmath.so. Lua expects vecmath.so, so rename it:

cp zig-out/lib/libvecmath.so vecmath.so

Or if you prefer, add this to your Lua test scripts:

package.cpath = package.cpath .. ";./lib?.so"

Now test it from Lua:

local vm = require("vecmath")
print(vm)

You should see Hello Lua printed to the console. We have a working dylib.

First functions

At this point I can imagine you thinking: “Hey, I can do this with the pure Lua C API, and it is even simpler! What is zua providing aside from boilerplate?” And you are right. Right now we have a glorified and overengineered hello world. But from this point on you will not need to call push again. Never. You will not even see the Lua bindings again.

Lets start doing something useful. A vector library needs vectors, so lets create one.

Create a file called src/vec2.zig:

const std = @import("std");
const zua = @import("zua");

pub const Vec2 = struct {
    x: f64,
    y: f64,
};

Now in src/main.zig, add the import and change the push line (the rest stays the same as setup):

const Vec2 = @import("vec2.zig").Vec2;

export fn luaopen_vecmath(L: *lua.State) c_int {
    // ... threaded io, libState, context init (same as before) ...
    zua.Mapper.Encoder.push(&ctx, Vec2{ .x = 20.0, .y = 30.0 }) catch return 0;
    return 1;
}

Build it and run from Lua:

local vm = require("vecmath")
print(vm.x, vm.y)

You will see 20 30 printed.

Maybe if you are not familiar with the Lua C API you will think “Thats all? You just push a struct into Lua?” But for those more familiar with the C API, notice what we did not do: create a table, push values on the stack, set keys one by one. We just pushed it and it worked. All that hard work was handled by zua at comptime.

But even now, our library is still kind of useless. We only return one fixed vector. Lets improve it by adding a function to create vectors. On zua it is as simple as writing a plain Zig function:

fn vec2(x: f64, y: f64) Vec2 {
    return .{ .x = x, .y = y };
}

Now push the function instead of the fixed vector (again, same setup, only the push line changes):

zua.Mapper.Encoder.push(&ctx, vec2) catch return 0;

Build it and try it from Lua:

local vm = require("vecmath")

local a = vm.vec2(3, 4)
local b = vm.vec2(1, 2)
local c = vm.vec2(10, 20)

print(a.x, a.y)
print(b.x, b.y)
print(c.x, c.y)

That is it. Create a Zig function, return a Zig struct, and use it from Lua. All the encoding and decoding happen automatically. That single push call creates at compile time all the optimized paths that call the required Lua API functions to encode the function and its return type and decode the function arguments. The only runtime behavior is calling the Lua API to check types and interact with the stack.

We went from an overengineered hello world to a usable vector builder in less than 10 lines of new code.

Shapes and Context

If you keep playing with what we did so far, you will notice that trying to print our vectors gives something like table: 0x7f8a4b2040c0. That is the default behavior for all Lua tables and it is ugly.

Those who come from Lua know what comes next, but since zig is not Lua I need to first explain one of the hearts of the zua library, Shapes.

What is a Shape?

You might ask, with all the reason in the world. A Shape is the API that zua provides to customize how the encoder “shapes” Zig data into Lua values and how it “shapes” Lua values back into Zig data.

Note

Shape is maybe not the best name, but it is well known that programmers suck at naming things and I am not the exception.

The declaration is simple, you must define a public constant called ZUA_SHAPE on your type. This is required because the data must be available at comptime.

There are several available shapes, each designed for a different usage and different Zig types. For now we will use the most simple one: Shape.Table.

Modify Vec2 like this:

pub const Vec2 = struct {
    x: f64,
    y: f64,

    pub const ZUA_SHAPE = zua.Shape.Table(Vec2, .{}, .{});
};

Note

For those not familiar with Zig: comptime is one of Zig’s biggest strengths. It lets you execute normal Zig code at compilation time. The work happens only once, allowing you to precompute values or choose better paths for certain types, and then use them at runtime without extra effort.

You will notice two empty .{} in the Shape.Table call. Each one configures different behavior for the type. For now we will leave them with the defaults.

If you run the code now you will notice that nothing changed. That is because the default strategy for Zig structs is already a Lua table. But now that we have the Shape declared, we can start adding what Lua users expect, methods and metamethods.

Adding __tostring

Lua has operator overloading, including string conversion. When Lua needs to convert a table to a string, it looks for a __tostring key in the table’s metatable and calls it with the table as argument. zua provides a straightforward way to add methods and metamethods.

First we need a function that returns a string representation. Lets start simple, without using the actual vector values:

fn toString(_: Vec2) []const u8 {
    return "Vec2";
}

As you can see it receives a copy of the vector. We ignore it with _ because we do not use it yet. “Wait, what? That is useless!” you might think. And yes, it is useless. But what can we do? We need an allocator to format a string at runtime. Zig has std.heap.c_allocator, std.heap.page_allocator, and std.heap.debug_allocator, but they will leak because we never free the memory.

Note

For those who never touched a low level language before: when you allocate memory you are responsible for freeing it. Otherwise you accumulate unused memory until either your program dies (on a good OS) or your computer dies (on a bad OS). Especially now that RAM is so expensive.

That is where the Context we talked about so long comes to rescue us.

Context and the arena

Every zua function can have *zua.Context as its first parameter. Context is our primary tool to communicate the Zig world with the Lua world. It holds the state, but it also holds exactly what we need for our never-free problem, an arena allocator.

Note

An arena allocator is a special kind of allocator that does not need individual frees. You allocate as much as you want and at the end of the lifetime you free everything in a single call.

The context is an ephemeral value that lives only from function call to result push on the Lua stack. That means you can return arena-allocated types, they survive long enough to be pushed to Lua, and then the arena is released safely.

Context also serves another purpose, failing. Those with experience in the Lua API know lua_error and its longjmp. It is a beautiful mechanism for error propagation, but it has a big problem in the Zig context: it skips defer statements, and defer is the main mechanism in Zig for cleanup. zua solves this with Context. You do not call lua_error. You make your return type an error union and return a normal Zig error. The error message is handled the same way: just return ctx.failTyped(ReturnType, "message").

Note

For those who do not know what longjmp and defer are: lua_error uses a C mechanism called longjmp that jumps out of the current function directly to an error handler, skipping any cleanup code in between. Zig’s defer runs cleanup code when a scope exits normally. If a longjmp skips the scope exit, the deferred code never runs. zua avoids this by not calling lua_error directly inside your function. It records the error and raises it after your function returns, so defer works correctly.

Knowing this, our toString becomes:

fn toString(ctx: *zua.Context, self: Vec2) ![]const u8 {
    return std.fmt.allocPrint(ctx.arena(), "vec2({d}, {d})", .{ self.x, self.y })
        catch ctx.failTyped([]const u8, "out of memory");
}

Note

ctx is optional. If you do not need the arena allocator, IO access, or the Lua state, you can leave it out. The ! in the return type is not optional: allocations can fail in Zig, so you must either handle the error (return a default value) or forward it. Forwarding means Lua users using pcall can catch the error and decide what to do.

Now we need to connect this function to the Shape. The first .{} in Shape.Table is the method map. Add __tostring there:

pub const ZUA_SHAPE = zua.Shape.Table(Vec2, .{
    .__tostring = toString,
}, .{});

Rebuild and test:

local vm = require("vecmath")
local a = vm.vec2(3, 4)
print(a)

Instead of table: 0x... you will see vec2(3, 4).

Methods and metamethods

We have a nice printed vector now, but the library is called vecmath. We have the vec, but not too much math yet. Before we add the operators, I need to explain something that might be confusing if you come from Zig and not Lua: methods and metamethods.

Methods in Lua

Lua does not have classes. It has tables and functions. A method is just a function stored in a table. When you write:

local a = vm.vec2(3, 4)
print(a.length(a))

That works, but it is verbose. Lua provides sugar for this, the : syntax. a:length() is exactly equivalent to a.length(a). The compiler inserts the table itself as the first argument.

On the Zig side, zua handles this automatically. When you declare a method in ZUA_SHAPE, the first parameter after ctx (if present) is the receiver. If your function takes self: Vec2, zua decodes it from the Lua call. You never see the colon syntax from Zig. You just write a function that takes the receiver as a parameter.

Note

Technically you do not need to have the same type as the first argument of a method. You can put any function there and call it with . syntax instead of : and it will work. However, the docs generator will get confused. For standalone functions the Shape.Fn mechanism is preferred. It will be discussed later.

Metamethods

Metamethods are methods with a special name that Lua calls automatically when you use an operator. They start with __. __tostring is one: Lua calls it when you pass the value to print() or tostring(). __add is another: Lua calls it when you use +.

The difference is simple:

  • Methods are called explicitly with : syntax: a:length().
  • Metamethods are called implicitly by Lua when you use an operator: a + b.

Both are declared the same way in ZUA_SHAPE. The __ prefix tells zua to register them in the metatable instead of the regular method list.

Note

For performance we do not create a new metatable for each value. Instead they are cached in the zua state and attached when the type is returned by the encoder.

Adding the operators

Now that we know the difference, lets add __add, __sub, __mul, and __eq. The pattern is the same as __tostring, write a Zig function and add it to the method map.

fn add(self: Vec2, other: Vec2) Vec2 {
    return .{ .x = self.x + other.x, .y = self.y + other.y };
}

fn sub(self: Vec2, other: Vec2) Vec2 {
    return .{ .x = self.x - other.x, .y = self.y - other.y };
}

fn mul(self: Vec2, factor: f64) Vec2 {
    return .{ .x = self.x * factor, .y = self.y * factor };
}

fn eq(a: Vec2, b: Vec2) bool {
    return a.x == b.x and a.y == b.y;
}

Notice __mul takes a Vec2 and an f64, not two Vec2s. Lua passes the right operand as the second argument regardless of its type. zua decodes it into whatever type the parameter declares, so scalar multiplication works naturally.

Note

If you pass the wrong argument type, zua gives you an error message like arg1: expected f64, got table. The “arg1” part is not very helpful. We will learn how to customize error messages later and replace those generic names with the actual parameter name.

__eq returns bool, not Vec2. Each metamethod has its own return contract: __add returns the same type, __eq returns a boolean, __tostring returns a string. zua does not enforce this. You just write the Zig function with the return type that makes sense, and zua encodes it.

Now add the named methods too. Same pattern:

fn length(self: Vec2) f64 {
    return @sqrt(self.x * self.x + self.y * self.y);
}

fn dot(a: Vec2, b: Vec2) f64 {
    return a.x * b.x + a.y * b.y;
}

fn normalize(self: Vec2) Vec2 {
    const len = @sqrt(self.x * self.x + self.y * self.y);
    if (len == 0) return .{ .x = 0, .y = 0 };
    return .{ .x = self.x / len, .y = self.y / len };
}

These work the same way, they just use : syntax instead of operators.

Register everything in the method map alongside __tostring:

pub const ZUA_SHAPE = zua.Shape.Table(Vec2, .{
    .__tostring = toString,
    .__add = add,
    .__sub = sub,
    .__mul = mul,
    .__eq = eq,
    .length = length,
    .dot = dot,
    .normalize = normalize,
}, .{});

Now build and test:

local vm = require("vecmath")

local a = vm.vec2(3, 4)
local b = vm.vec2(1, 2)

local c = a + b
print(c)

local d = a - b
print(d)

local e = a * 2
print(e)

print(a == vm.vec2(3, 4))
print(a == b)

You will see vec2(4, 6), vec2(2, 2), vec2(6, 8), true, and false.

Methods and metamethods follow the same rule: write a plain Zig function, add it to the ZUA_SHAPE method map, and it works. The only difference is who calls them.

Modules

We have a working Vec2 with methods, operators, and nice printing. But I also promised Vec3. Vec3 is in essence Vec2 with an extra component and a cross product, so lets just create it in lib/vec3.zig:

const std = @import("std");
const zua = @import("zua");

pub const Vec3 = struct {
    x: f64,
    y: f64,
    z: f64,

    pub const ZUA_SHAPE = zua.Shape.Table(Vec3, .{
        .__add = add,
        .__sub = sub,
        .__mul = mul,
        .__eq = eq,
        .length = length,
        .dot = dot,
        .cross = cross,
        .normalize = normalize,
        .__tostring = toString,
    }, .{});

    fn add(a: Vec3, b: Vec3) Vec3 { return .{ .x = a.x + b.x, .y = a.y + b.y, .z = a.z + b.z }; }
    fn sub(a: Vec3, b: Vec3) Vec3 { return .{ .x = a.x - b.x, .y = a.y - b.y, .z = a.z - b.z }; }
    fn mul(self: Vec3, factor: f64) Vec3 { return .{ .x = self.x * factor, .y = self.y * factor, .z = self.z * factor }; }
    fn eq(a: Vec3, b: Vec3) bool { return a.x == b.x and a.y == b.y and a.z == b.z; }
    fn length(self: Vec3) f64 { return @sqrt(self.x * self.x + self.y * self.y + self.z * self.z); }
    fn dot(a: Vec3, b: Vec3) f64 { return a.x * b.x + a.y * b.y + a.z * b.z; }
    fn cross(a: Vec3, b: Vec3) Vec3 { return .{ .x = a.y * b.z - a.z * b.y, .y = a.z * b.x - a.x * b.z, .z = a.x * b.y - a.y * b.x }; }
    fn normalize(self: Vec3) Vec3 {
        const len = @sqrt(self.x * self.x + self.y * self.y + self.z * self.z);
        if (len == 0) return .{ .x = 0, .y = 0, .z = 0 };
        return .{ .x = self.x / len, .y = self.y / len, .z = self.z / len };
    }
    fn toString(ctx: *zua.Context, self: Vec3) ![]const u8 {
        return std.fmt.allocPrint(ctx.arena(), "vec3({d}, {d}, {d})", .{ self.x, self.y, self.z }) catch
            ctx.failTyped([]const u8, "oom");
    }
};

As you can see it is basically the same, just a couple extra functions. Nothing new on the Lua side.

Now lets add the constructor functions to main.zig:

fn vec3_fn(x: f64, y: f64, z: f64) Vec3 {
    return .{ .x = x, .y = y, .z = z };
}

Now lets push one of them and test. But wait, can we push both? What happens if we push vec2 and then vec3? Does the user write local vec2, vec3 = require("vecmath")? Or local vecmath = require("vecmath") and then what?

The module problem

In Lua, require("name") expects a single return value. Lua supports multiple returns, but require specifically looks for the first value and ignores the rest. Pushing two functions means the second one is lost.

Note

I am not fully sure if this still applies to Lua 5.4, the threads I found about it are pretty old (like this one). But in most places and guides the recommendation is always to return only one value from require.

So how do you expose multiple things? The answer is the same pattern Lua itself uses for modules: return a table. A table with named fields works like a namespace. require sees one value (the table), and the user accesses everything through it.

Maybe some of you expect an intricate solution or some complex mechanism. The reality is simpler. Lua is a simple language, so we have a hammer called table and this is a nail.

Lets then move everything into a new file like lib/module.zig:

const std = @import("std");
const zua = @import("zua");

const Vec2 = @import("vec2.zig").Vec2;
const Vec3 = @import("vec3.zig").Vec3;

fn vec2_fn(x: f64, y: f64) Vec2 {
    return .{ .x = x, .y = y };
}

fn vec3_fn(x: f64, y: f64, z: f64) Vec3 {
    return .{ .x = x, .y = y, .z = z };
}

pub const Vecmath = struct {
    vec2: zua.Shape.Fn(vec2_fn, .{}) = .{},
    vec3: zua.Shape.Fn(vec3_fn, .{}) = .{},
};

Note

Yes, another empty .{}. You might be wondering what that is for and what Shape.Fn even is. All that will be explained in the next chapter.

Vecmath is a plain struct with no ZUA_SHAPE. The default strategy for Zig structs is a Lua table, and zua pushes each field as a Lua callable automatically. You could add more functions here and they would just appear as new fields in the module table.

Now main.zig becomes cleaner:

const std = @import("std");
const zua = @import("zua");
const lua = zua.Bindings.lua;

const Vecmath = @import("lib/module.zig").Vecmath;

export fn luaopen_vecmath(L: *lua.State) c_int {
    var threaded = std.Io.Threaded.init(std.heap.c_allocator, .{});
    const io = threaded.io();

    const state = zua.State.libState(L, std.heap.c_allocator, io, "vecmath") catch return 0;
    var ctx = zua.Context.init(state);
    defer ctx.deinit();
    zua.Mapper.Encoder.push(&ctx, Vecmath{}) catch return 0;
    return 1;
}

The entry point just imports the module and pushes it. Everything else lives in lib/.

Using it from Lua

Lets see if it works with this example:

local vm = require("vecmath")

print(vm)

local a = vm.vec2(3, 4)
local b = vm.vec3(1, 2, 3)

print(a:length(), b:length())
print(b:cross(vm.vec3(0, 1, 0)))

As you can see it returns a table. The table has our two functions, and we can still use them to generate vectors with all their methods. And we still have the same single push, I promise no stack playing, and as promised that is the only push we will do in the whole project.

More module functions

Before we move on there is some unfinished business. A vector math library without lerp, transforms, and matrix application is not much of a vector math library. None of this teaches anything new about zua, but you need it to have a complete example to follow along with.

The only thing worth pointing out is Transform:

const Transform = [3][3]f64;

A fixed-size array maps to a Lua table with integer keys, same as a struct maps to a table with field names. Nested arrays become nested tables. [3][3]f64 arrives in Lua as {{1,0,0},{0,1,0},{0,0,1}} with no extra work. Keep that in mind whenever you need to pass matrix-like data.

The rest is just math. Add these to lib/module.zig:

fn lerp_fn(a: Vec2, b: Vec2, t: f64) Vec2 {
    return .{ .x = a.x + (b.x - a.x) * t, .y = a.y + (b.y - a.y) * t };
}

fn identity_fn() Transform {
    return .{ .{ 1, 0, 0 }, .{ 0, 1, 0 }, .{ 0, 0, 1 } };
}

fn rotate_fn(t: Transform, angle: f64) Transform {
    const c = @cos(angle);
    const s = @sin(angle);
    return .{
        .{ t[0][0] * c + t[0][1] * s, -t[0][0] * s + t[0][1] * c, t[0][2] },
        .{ t[1][0] * c + t[1][1] * s, -t[1][0] * s + t[1][1] * c, t[1][2] },
        .{ t[2][0] * c + t[2][1] * s, -t[2][0] * s + t[2][1] * c, t[2][2] },
    };
}

fn scale_fn(t: Transform, factor: f64) Transform {
    return .{
        .{ t[0][0] * factor, t[0][1] * factor, t[0][2] * factor },
        .{ t[1][0] * factor, t[1][1] * factor, t[1][2] * factor },
        .{ t[2][0] * factor, t[2][1] * factor, t[2][2] * factor },
    };
}

fn apply_fn(t: Transform, v: Vec2) Vec2 {
    return .{
        .x = t[0][0] * v.x + t[0][1] * v.y + t[0][2],
        .y = t[1][0] * v.x + t[1][1] * v.y + t[1][2],
    };
}

Register them in Vecmath:

pub const Vecmath = struct {
    vec2: zua.Shape.Fn(vec2_fn, .{}) = .{},
    vec3: zua.Shape.Fn(vec3_fn, .{}) = .{},
    lerp: zua.Shape.Fn(lerp_fn, .{}) = .{},
    identity: zua.Shape.Fn(identity_fn, .{}) = .{},
    rotate: zua.Shape.Fn(rotate_fn, .{}) = .{},
    scale: zua.Shape.Fn(scale_fn, .{}) = .{},
    apply: zua.Shape.Fn(apply_fn, .{}) = .{},
};

And use them from Lua:

local mid = vm.lerp(a, b, 0.5)
print(mid.x, mid.y)

local t = vm.rotate(vm.scale(vm.identity(), 2), math.pi / 4)
local rotated = vm.apply(t, a)
print(rotated.x, rotated.y)

Docs

At this point we have a pretty decent library. But if you play with it you probably noticed an inconvenience: the LSP is not giving you any autocompletion at all. That is pretty obvious if we think about it. Lua only sees a machine code file with zero information about what your library does. We need to help Lua with that, and zua has exactly the tool for that.

The Lua language server supports definition-only files, where you define the shape of your library with zero code. zua provides a module to autogenerate this documentation. But too much talk. As Linux Torvalds says, talk is cheap, show me the code:

fn docs_fn(ctx: *zua.Context) ![]const u8 {
    return zua.Docs.generateModule(ctx.arena(), Vecmath{}, "vecmath");
}

Add it to lib/module.zig and register it in the Vecmath struct:

pub const Vecmath = struct {
    vec2: zua.Shape.Fn(vec2_fn, .{}) = .{},
    vec3: zua.Shape.Fn(vec3_fn, .{}) = .{},
    docs: zua.Shape.Fn(docs_fn, .{}) = .{},
};

Now call it from Lua:

local vm = require("vecmath")
local stubs = vm.docs()
print(stubs)

The output looks like this:

---@meta vecmath

---@class Vec2
---@operator add(Vec2): Vec2
---@operator sub(Vec2): Vec2
---@operator mul(number): Vec2
---@field x number
---@field y number
local Vec2 = {}

---@class Vec3
---@operator add(Vec3): Vec3
---@operator sub(Vec3): Vec3
---@operator mul(number): Vec3
---@field x number
---@field y number
---@field z number
local Vec3 = {}

---@class Vecmath
local Vecmath = {}

---@return Vec2
function Vec2:normalize() end

---@return Vec3
function Vec3:normalize() end

---@return number
function Vec2:length() end

---@param arg1 number
---@param arg2 number
---@return Vec2
function Vecmath.vec2(arg1, arg2) end

---@param arg1 number
---@param arg2 number
---@param arg3 number
---@return Vec3
function Vecmath.vec3(arg1, arg2, arg3) end

---@return string
function Vecmath.docs() end

return Vecmath

Save those stubs to a file and open it in your editor. The autocompletion works. But look closely at the function signatures: arg1, arg2, arg3. Not exactly helpful. And the classes have no descriptions. That is all the information zua had to work with, because Zig doc comments do not survive to comptime. The empty .{} arguments we have been leaving on every Shape call are where that information goes.

Note

---@meta vecmath means the file is definitions only and applies to require("vecmath"). Class declarations are Lua’s way of defining a table shape with its fields, operators, and methods. return Vecmath at the end is a contract saying whatever require returns matches this class.

Now write a script to save the stubs to a file:

local vm = require("vecmath")
local stubs = vm.docs()
local file = io.open("vecmath.d.lua", "w")
file:write(stubs)
file:close()
print("stubs written to vecmath.d.lua (" .. #stubs .. " bytes)")

Warning

If your editor does not automatically recognize the .d.lua file, you must configure your .luarc.json. Unfortunately that is out of the scope of the book, but the information is widely spread on the internet.

Shape options

Every .{} we left empty along the way was a small debt. Time to pay it back.

Lets start fixing the function argx issue first, since it is the more confusing piece. Everything else has a name, only args has default ones.

Take the Shape.Fn on vec2_fn in module.zig:

zua.Shape.Fn(vec2_fn, .{})

That empty .{} can take a description and a list of arguments:

zua.Shape.Fn(vec2_fn, .{
    .description = "Construct a new Vec2 value.",
    .args = &.{
        .{ .name = "x", .description = "Horizontal component." },
        .{ .name = "y", .description = "Vertical component." },
    },
})

Now the stub generator writes ---@param x number # Horizontal component. instead of ---@param arg1 number.

The Table options work the same way. The second .{} we have been leaving empty:

zua.Shape.Table(Vec2, .{...}, .{
    .name = "Vec2",
    .description = "A 2D vector with component-wise operations.",
    .field_descriptions = .{
        .x = "Horizontal component.",
        .y = "Vertical component.",
    },
})

The .name sets the class name in stubs. Remember the note in the methods chapter about arg1: expected f64, got table being unhelpful? With .args on the functions, that error turns into x: expected f64, got string.

One more thing worth knowing: if you rename x to x_coord in Vec2 and forget to update field_descriptions, it breaks at compile time. Docs cannot go stale without you knowing about it.

Now update Vecmath with all this. Add ZUA_SHAPE back with the module name, and wrap the functions with Fn options:

const Transform = [3][3]f64;

const Vecmath = struct {
    pub const ZUA_SHAPE = zua.Shape.Table(Vecmath, .{}, .{
        .name = "vecmath",
    });

    vec2: zua.Shape.Fn(vec2_fn, .{
        .description = "Construct a new Vec2 value.",
        .args = &.{
            .{ .name = "x", .description = "Horizontal component." },
            .{ .name = "y", .description = "Vertical component." },
        },
    }) = .{},
    vec3: zua.Shape.Fn(vec3_fn, .{
        .description = "Construct a new Vec3 value.",
        .args = &.{
            .{ .name = "x", .description = "X component." },
            .{ .name = "y", .description = "Y component." },
            .{ .name = "z", .description = "Z component." },
        },
    }) = .{},
    lerp: zua.Shape.Fn(lerp_fn, .{
        .description = "Linearly interpolate between two Vec2 values.",
        .args = &.{
            .{ .name = "a", .description = "Starting vector." },
            .{ .name = "b", .description = "Ending vector." },
            .{ .name = "t", .description = "Interpolation factor (0.0 to 1.0)." },
        },
    }) = .{},
    identity: zua.Shape.Fn(identity_fn, .{
        .description = "Create an identity 3x3 transform matrix.",
    }) = .{},
    rotate: zua.Shape.Fn(rotate_fn, .{
        .description = "Rotate a transform matrix around the Z axis.",
        .args = &.{
            .{ .name = "t", .description = "Transform matrix." },
            .{ .name = "angle", .description = "Rotation angle in radians." },
        },
    }) = .{},
    scale: zua.Shape.Fn(scale_fn, .{
        .description = "Uniformly scale a transform matrix.",
        .args = &.{
            .{ .name = "t", .description = "Transform matrix." },
            .{ .name = "factor", .description = "Scale factor." },
        },
    }) = .{},
    apply: zua.Shape.Fn(apply_fn, .{
        .description = "Apply a transform to a Vec2.",
        .args = &.{
            .{ .name = "t", .description = "Transform matrix." },
            .{ .name = "v", .description = "Vector to transform." },
        },
    }) = .{},
    docs: zua.Shape.Fn(docs_fn, .{
        .description = "Generate editor stubs for the vecmath module.",
    }) = .{},
};

Rebuild and run the docs script again and vec2 looks like this:

---@class Vec2
---@field x number # Horizontal component.
---@field y number # Vertical component.
-- A 2D vector with component-wise operations.
local Vec2 = {}

-- Construct a new Vec2 value.
---@param x number # Horizontal component.
---@param y number # Vertical component.
---@return Vec2
function vecmath.vec2(x, y) end

Now we have the module level documentation solved. But if you look deeper, we are not done yet. The vector methods still have arg1 and so on.

How to document methods

Documenting methods works the same way as module functions. First add the import at the top of your Zig file:

const Modifier = zua.Shape.Modifier;

Then use bare functions for methods that need no documentation, and Modifier.Method when you need description or args:

.__add = Modifier.Method(add, .{ .description = "Component-wise addition." }),
.dot = Modifier.Method(dot, .{ .description = "Dot product.", .args = &.{.{ .name = "b" }} }),

For metamethods only description is needed, Lua already knows their arguments. For regular methods you add .args to name the parameters.

The disadvantage of this approach is that the shape becomes dense and hard to read, especially when you have several methods. Pulling the methods out into their own constant keeps it cleaner:

const methods = .{
    .__add = Modifier.Method(add, .{ .description = "Component-wise addition." }),
    .dot = Modifier.Method(dot, .{ .description = "Dot product.", .args = &.{.{ .name = "b" }} }),
    ...
};

pub const ZUA_SHAPE = zua.Shape.Table(Vec2, methods, .{ ... });

This separates method documentation from the shape, keeping a cleaner structure.

Or if you want each method to carry its own documentation, you can define it as a const:

fn addImpl(a: Vec2, b: Vec2) Vec2 { ... }
const add = Modifier.Method(addImpl, .{ .description = "Component-wise addition." });

The method map stays clean with just .__add = add without docs noise. I prefer the extracted constant approach, keeps ZUA_SHAPE short and the methods section is its own block. But the inline form works fine if you do not want the extra indirection.

Using my preference the Vec2 and Vec3 methods constants will look something like this.

Note

It will vary a lot depending on what you prefer. The content of the docs will be the same but the way you write it will vary.

const methods = .{
    .__add = Modifier.Method(add, .{ .description = "Component-wise addition." }),
    .__sub = Modifier.Method(sub, .{ .description = "Component-wise subtraction." }),
    .__mul = Modifier.Method(mul, .{ .description = "Scalar multiplication." }),
    .__eq = Modifier.Method(eq, .{ .description = "Equality comparison." }),
    .length = Modifier.Method(length, .{ .description = "Euclidean norm." }),
    .dot = Modifier.Method(dot, .{ .description = "Dot product.", .args = &.{.{ .name = "b", .description = "Right vector." }} }),
    .normalize = Modifier.Method(normalize, .{ .description = "Unit vector, returns zeros if length is zero." }),
    .__tostring = toString,
};

pub const ZUA_SHAPE = zua.Shape.Table(Vec2, methods, .{ ... });

// ... rest of the struct stays the same ...

const methods = .{
    .__add = Modifier.Method(add, .{ .description = "Component-wise addition." }),
    .__sub = Modifier.Method(sub, .{ .description = "Component-wise subtraction." }),
    .__mul = Modifier.Method(mul, .{ .description = "Scalar multiplication." }),
    .__eq = Modifier.Method(eq, .{ .description = "Equality comparison." }),
    .length = Modifier.Method(length, .{ .description = "Euclidean norm." }),
    .dot = Modifier.Method(dot, .{ .description = "Dot product.", .args = &.{.{ .name = "b", .description = "Right vector." }} }),
    .cross = Modifier.Method(cross, .{ .description = "Cross product.", .args = &.{.{ .name = "b", .description = "Right vector." }} }),
    .normalize = Modifier.Method(normalize, .{ .description = "Unit vector, returns zeros if length is zero." }),
    .__tostring = toString,
};

pub const ZUA_SHAPE = zua.Shape.Table(Vec3, methods, .{ ... });

Run the docs script again and the stubs now include descriptions for methods:

-- Dot product.
---@param b Vec2 # Right vector.
---@return number
function Vec2:dot(b) end

-- Euclidean norm.
---@return number
function Vec2:length() end

-- Unit vector, returns zeros if length is zero.
---@return Vec2
function Vec2:normalize() end

Now we have a complete generated docs. I know it is a bit verbose, but it looks way better and believe me your Lua users will thank you. It will also serve you since now you will be able to test without needing to read the Zig code, and even better it will be in sync with your code. If you rename a field it will tell you are trying to document something that does not exist. And if you do not need docs, just leave .{}, nobody will complain.

Objects

At this point you have a complete vector library. You can create vectors, operate on them, lerp between them, and apply transforms. Everything works. But if you stop and think about it, is this really faster than writing the same thing in pure Lua?

Honestly, not by much. Every operation has to decode the input tables into Zig structs, do the math, then encode the result back into a new Lua table. That is a lot of table creation and field hashing just to add two vectors. The only real gain is the lexing, parsing, and compiling time for the math itself, but the overhead of pushing data back and forth eats most of that advantage.

To get real performance we need to skip the table encoding and decoding entirely. That is what Objects are for.

What is an Object

An Object is zua’s name for what Lua calls heavy userdata. The rename felt necessary because “userdata” is not exactly descriptive from a user’s perspective, but under the hood they are the same thing.

An Object is a Zig value allocated directly in Lua memory. It lives as long as something in Lua references it. When Lua’s garbage collector determines it is no longer reachable, it runs __gc and frees the memory. The data is opaque to Lua, which sounds like a disadvantage, but it plays in our favor. Instead of fields scattered as individual Lua table entries with hashing and reference counting overhead, the entire struct sits in a packed, cache-friendly block of memory.

Changing Table to Object

The change is almost insultingly simple. Take Vec2:

pub const ZUA_SHAPE = zua.Shape.Table(Vec2, .{ ... }, .{
    .name = "Vec2",
    .description = "A 2D vector with component-wise operations.",
    .field_descriptions = .{ .x = "X component.", .y = "Y component." },
});

Change Table to Object and drop field_descriptions, Object options only take name and description:

pub const ZUA_SHAPE = zua.Shape.Object(Vec2, .{ ... }, .{
    .name = "Vec2",
    .description = "A 2D vector with component-wise operations.",
});

Same for Vec3. Build and test it. Methods and operators still work. But a.x and a.y will not. The struct is now opaque memory from Lua’s perspective, so there are no fields to look up.

Making fields accessible

zua provides Modifier.Field to generate __index and __newindex entries for specific fields automatically. Change the field declarations from plain types:

x: f64,
y: f64,

to field modifiers:

x: zua.Shape.Modifier.Field(f64, .{ .description = "X component." }),
y: zua.Shape.Modifier.Field(f64, .{ .description = "Y component." }),

Now a.x and a.y = 5 work again. Modifier.Field(f64, ...) wraps the f64 in a thin struct with a single .value field. Your Zig code reads and writes through .value. Lua reads and writes through the generated __index and __newindex. From either side it is the same f64 sitting in memory, there is no conversion.

Updating the method signatures

With Table strategy, methods received Vec2 by value because zua decoded the table into a fresh struct copy on every call. With Object strategy, the data already lives in Lua memory. zua can hand you a pointer directly.

Start with Vec2 by value and it works:

fn add(self: Vec2, other: Vec2) Vec2 {
    return .{ .x = .new(self.x.value + other.x.value), .y = .new(self.y.value + other.y.value) };
}

But each call copies the entire struct out of the userdata and into a local. For a two-field struct that is cheap, but it adds up in a hot loop. Switch to a pointer and the copy disappears:

fn add(self: *Vec2, other: *Vec2) Vec2 {
    return .{ .x = .new(self.x.value + other.x.value), .y = .new(self.y.value + other.y.value) };
}

Now self and other point directly into the Lua userdata memory. No copy. But there is a problem. A *Vec2 lets you write through the pointer, and none of these functions actually modify their inputs. Leaving the pointer mutable means you might accidentally mutate a vector that Lua still holds a reference to, which produces the kind of bug that is very hard to track down.

Mark them *const and the compiler closes that door entirely:

fn add(self: *const Vec2, other: *const Vec2) Vec2 {
    return .{ .x = .new(self.x.value + other.x.value), .y = .new(self.y.value + other.y.value) };
}

*const tells the compiler these pointers will never be written through. Beyond preventing the accidental mutation, it also allows the compiler to add optimizations it could not apply to a mutable pointer, since it now knows the memory behind them cannot change during the call.

Apply the same pattern to all Vec2 and Vec3 methods, and to the module-level functions that take vectors:

fn lerp_fn(a: *const Vec2, b: *const Vec2, t: f64) Vec2 {
    return .{
        .x = .new(a.x.value + (b.x.value - a.x.value) * t),
        .y = .new(a.y.value + (b.y.value - a.y.value) * t),
    };
}

fn apply_fn(t: Transform, v: *const Vec2) Vec2 {
    return .{
        .x = .new(t[0][0] * v.x.value + t[0][1] * v.y.value + t[0][2]),
        .y = .new(t[1][0] * v.x.value + t[1][1] * v.y.value + t[1][2]),
    };
}

Note

If you want a field the Lua user can read but not write, use Modifier.Value instead of Modifier.Field. Only __index is generated, and any write attempt from Lua will error with a clear message.

Performance

Now the library is genuinely faster than a pure Lua version. The critical path, vector addition, dot product, lerp, transforms, operates directly on packed struct memory without creating or destroying any Lua tables. The only allocation per operation is the new userdata returned as the result, and that is managed by Lua’s own allocator.

The general rule is: the more data you push through the Lua table boundary, the slower your library becomes. Move critical data and heavy operations to Zig. Expose only what the Lua user needs to read or write through Field and Value. Every chunk of work that stays on the Zig side is a chunk that does not pay the encoding and decoding tax.

Thanks for coming this far. Have a great time using zua :3