How to specify user project specific options for a .zon dependency

First time user of a project using a .zon declared dependency. I’m trying to depend on the Ziglua project which declares a .zon file that I make my own project depend on like below:

pub fn build(b: *std.Build) void {
    // ... snip ...

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

    // ... snip ...

    // add the ziglua module and lua artifact
    exe.addModule("ziglua", ziglua.module("ziglua"));
    exe.linkLibrary(ziglua.artifact("lua"));
}

However, the Ziglua project exposes various project specific settings, such as which Lua version it uses. When compiling the Ziglua project and its examples, I can specify this like so:

zig build -Dversion=luau test

But how do I specify the same in my own application’s build.zig so that zig build builds the right flavor of Ziglua?

It helps to first look at what the Ziglua build.zig does, especially these two snippets of code:

What you want to do is to define similar options in your own build.zig, then include them in your args struct in your b.depdendency call to forward them to Ziglua.

The shared option is pretty simple since it’s just a boolean. For the version option you will need to import the LuaVersion enum from the Ziglua build.zig, which you should be able to do with @import("ziglua").

You will end up with something like this:

const std = @import("std");

// This imports the Ziglua 'build.zig' file just like a normal import.
const ziglua_build_zig = @import("ziglua");

pub fn build(b: *std.Build) void {
    // ...

    const ziglua_version = b.option(ziglua_build_zig.LuaVersion, "ziglua-version", "...") orelse .lua_54;
    const ziglua_shared = b.option(bool, "ziglua-shared", "...") orelse false;

    const ziglua = b.dependency("ziglua", .{
        .target = target,
        .optimize = optimize,
        .version = ziglua_version,
        .shared = ziglua_shared,
    });

    // ...
}

Let me know if something like this works (I haven’t tested it but I believe it should work).

6 Likes

Excellent, I’m glad I asked! I’ll give it a shot and report the outcome here.

It works! Thank you very much, @castholm!

Here’s a working example (which I’ll also send a PR for to the Ziglua project):

    const ziglua = b.dependency("ziglua", .{
        .target = target,
        .optimize = optimize,
        .version = @import("ziglua").LuaVersion.luau,
    });

    const exe = b.addExecutable(.{
        .name = "luau-example",
        .root_source_file = .{ .path = "src/main.zig" },
        .target = target,
        .optimize = optimize,
    });

    // add the ziglua module and lua artifact
    exe.addModule("ziglua", ziglua.module("ziglua"));
    exe.linkLibrary(ziglua.artifact("luau"));
6 Likes