0

In Zig, I can do this with no problems:

fn foo() void {
    comptime var num: comptime_int = 0;
    num += 1;
}

But when I try declaring the variable outside of a function, I get a compile error:

comptime var num: comptime_int = 0;

fn foo() void {
    num += 1;
}

fn bar() void {
    num += 2;
}
error: expected block or field, found 'var'

Zig version: 0.9.0-dev.453+7ef854682

Dull Bananas
  • 892
  • 7
  • 29

1 Answers1

2

Use the method used in zorrow. It defines the variable in a function (a block works too), then it returns a struct with functions for accessing it.

You can create a struct that defines get and set functions:

const num = block_name: {
    comptime var self: comptime_int = 0;

    const result = struct {
        fn get() comptime_int {
            return self;
        }

        fn increment(amount: comptime_int) void {
            self += amount;
        }
    };

    break :block_name result;
};

fn foo() void {
    num.increment(1);
}

fn bar() void {
    num.increment(2);
}

In the future, you will be able to use a const with a pointer to the mutable value, and the method shown above will no longer be allowed by the compiler: https://github.com/ziglang/zig/issues/7396

Dull Bananas
  • 892
  • 7
  • 29
  • Above code doesn't work on zig-0.9.1 parameter of type 'comptime_int' must be declared comptime "fn increment(amount: comptime_int) void {". I fix it with "fn increment(comptime amount: comptime_int) void {". However it is still not working: after increment, the `num.get()` is still zero. – YouJiacheng Aug 08 '22 at 07:58