Guide · Chapter 1 of 14

Types, control flow, and imports

Read data layout, expressions, and diagnostics through the 6510's byte and word model.

Jump to a section

Program shape and imports

An executable declares export fn main() void. The compiler resolves @import("c64") and @import("ZeroPage") internally. Import local .zp64 source files for code compiled into the same PRG. A typed DLL import has a separate lifecycle, covered in the DLL chapter.

06_module_main.zp64
const c64 = @import("c64");
const math = @import("06_module_math.zp64");

export fn main() void {
    c64.screen.clear();
    c64.screen.putsAt(2, 2, "MODULE DEMO");

    var total: u8 = math.add8(2, 5);
    var ok: bool = math.isEqual8(total, 7);
    if (ok == true) {
        c64.screen.putsAt(2, 5, "IMPORT CALL OK");
    }
    c64.screen.putsAt(2, 7, "TOTAL=");
    c64.screen.hexAt(8, 7, total);
    c64.screen.putsAt(12, 7, "OK=");
    c64.screen.hexAt(15, 7, ok);
}

Imported source file

Values, layout, and arithmetic

Use u8 and i8 for byte storage and u16, i16, or usize for words. Pointers are 16-bit near addresses. Words are little-endian and alignment is one byte. The compiler retains the destination width on arithmetic. Signed storage is available with a narrower set of arithmetic and comparison operations.

Fixed arrays are contiguous and limited to 255 bytes per array. Struct fields are flattened. Passing a record by value copies its fields. @sizeOf, @alignOf, and @offsetOf inspect supported layouts at compile time. Arrays serve as storage and have restricted by-value behavior.

25_struct_array_table.zp64
const c64 = @import("c64");

const Cell = enum(u8) { empty = 0, x = 1, o = 2 };
const Entry = struct { cell: Cell, value: u8, weight: u16 };

const table = [_]Entry{
    Entry{ .cell = .x, .value = 3, .weight = 100 },
    Entry{ .cell = .o, .value = 5, .weight = 200 },
    Entry{ .cell = .empty, .value = 7, .weight = 300 },
};

fn cellScore(cell: Cell) u8 {
    return switch (cell) {
        .x => 10,
        .o => 20,
        else => 0,
    };
}

fn tableValue(index: u8) u8 {
    return table[index].value + cellScore(table[index].cell);
}

export fn main() void {
    c64.console.clear();
    c64.console.print("struct array table\n", .{});

    var rows: [3]Entry = .{
        Entry{ .cell = .empty, .value = 1, .weight = 10 },
        Entry{ .cell = .empty, .value = 2, .weight = 20 },
        Entry{ .cell = .empty, .value = 3, .weight = 30 },
    };

    var sum: u8 = 0;
    for (rows, 0..) |_, i| {
        rows[i].cell = table[i].cell;
        rows[i].value = tableValue(i);
        rows[i].weight = table[i].weight + rows[i].value;
        sum += rows[i].value;
    }

    c64.console.print("sum {x}\n", .{sum});
    c64.console.print("mut {x} {x}\n", .{ rows[1].value, rows[2].weight });

    if (sum == 45 and rows[1].value == 25 and rows[2].weight == 307) {
        c64.console.print("struct array ok\n", .{});
        c64.vic.border = 5;
    } else {
        c64.console.print("struct array bad\n", .{});
        c64.vic.border = 2;
    }
}

Type and expression rules · Record layout and pointers in depth

Follow the carry from a byte into a word

Predict the two results for input 0xff. nextByte returns a byte, so adding one keeps the low eight bits, 00. nextWord widens the input first, so the carry reaches bit 8 and the result is 0100. Widening after a byte-valued call would preserve only the byte that call returned.

counter-width.zp64
const c64 = @import("c64");

fn nextByte(value: u8) u8 {
    return value + 1;
}

fn nextWord(value: u8) u16 {
    return @as(u16, value) + 1;
}

export fn main() void {
    c64.console.clear();
    const byte = nextByte(0xff);
    const word = nextWord(0xff);
    const high = word >> 8;
    const low = word & 0x00ff;

    c64.console.print("BYTE {x} WORD {x16}\n", .{ byte, word });
    c64.console.print("HIGH {x16} LOW {x16}\n", .{ high, low });
}

Open the complete source

The screen shows BYTE 00 WORD 0100 and HIGH 0001 LOW 0000. The inferred bindings from the calls retain the declared return widths. Shifting the word right by eight brings the high byte down. Masking with 0x00ff clears its high byte. Both expressions here still have word width.

This is a ZeroPage arithmetic rule. Ordinary supported arithmetic keeps the result bits of its target width, and Zig's explicit wrapping operators such as +% are rejected. Use a word before arithmetic when you need to retain the carry. Use unsigned values for shifts. A literal count must be less than the operand width, so word >> 8 works where shifting a byte by eight is rejected.

Word carry and borrow assertions · Masks and runtime shift counts · Inferred scalar bindings · Wrapping operator diagnostic

Branches, loops, and indexes

Open docs/tutorial-examples/colors.zp64 in the repository. Each keypress advances to the next color. Return exits the program.

colors.zp64
const c64 = @import("c64");

const colors = [_]u8{ 2, 5, 6 };

fn nextIndex(index: u8) u8 {
    if (index == 2) {
        return 0;
    }
    return index + 1;
}

export fn main() void {
    var index: u8 = 0;
    c64.console.clear();
    c64.vic.border = colors[index];
    c64.screen.hexAt(0, 0, index);
    var pressed = c64.keyboard.waitPetscii();
    while (pressed != c64.key.return_) {
        index = nextIndex(index);
        c64.vic.border = colors[index];
        c64.screen.hexAt(0, 0, index);
        pressed = c64.keyboard.waitPetscii();
    }
}

The fixed array has three bytes. nextIndex keeps the runtime index within bounds because generated indexing has no runtime bounds check. Use u8 for byte values and u16 or usize for words and addresses. Types, control flow, and language limits

and and or short-circuit. switch accepts scalar selectors, supported ranges, and optional or tagged-union payloads. for walks fixed arrays or zero-based fixed ranges. Array payloads are read-only copies. Literal out-of-range indexes fail compilation. Guard runtime indexes in application code.

Predict what happens when expressions have side effects

takeIndex returns index zero and advances the cursor. The update reads the original total of 5 before calling refresh. That call writes 55 into the same slot and returns 7. The final compound assignment stores 5 + 7, replacing the intermediate write.

indexed-update.zp64
const c64 = @import("c64");

fn takeIndex(cursor: *u8) u8 {
    const next = cursor.*;
    cursor.* = next + 1;
    return next;
}

fn refresh(slot: *u16) u16 {
    slot.* = 55;
    return 7;
}

export fn main() void {
    var cursor: u8 = 0;
    var totals = [_]u16{ 5, 20 };
    const first: *u16 = &totals[0];
    totals[takeIndex(&cursor)] += refresh(first);

    const total: u16 = totals[0];
    c64.console.clear();
    c64.console.print("TOTAL {x16} CURSOR {x}\n", .{ total, cursor });
}

Open the complete source

Expect TOTAL 000C CURSOR 01. The cursor advances once. In application code, split an update into separate statements when it helps readers see the order.

Choose a loop, a condition, or a value-producing branch

Use for (items, 0..) to visit a fixed table with its indexes. The capture is a value, so use the index to write back into mutable storage. Use while when the stopping point comes from input or a changing condition. A range-only for uses the supported zero-based fixed range. The loop and switch examples show the supported grammar in complete programs.

Use an if or switch expression when both paths compute a value. For several steps before the result, a labeled block returns a value with break :label value. Keep the result within the supported scalar subset.

Block expression from the control fixture
fn byteBlock(value: u8) u8 {
    return blk: {
        const base = value + 1;
        break :blk base + 2;
    };
}

Short-circuiting also controls whether work happens. A false left operand of and skips the right operand, and a true left operand of or skips it. The host fixture checks both the result and whether a helper ran. Use this pattern to guard an indexed read behind a bounds condition.

Fixed-array loop · Scalar switch dispatch · Short-circuit assertions

Dispatch input with exact values, lists, and ranges

The command table contains Return, Down, Space, and an unrecognized byte. The first switch maps them to 1, 2, 32, and 4. Those add to 39. The word-valued switch returns 512 for that exact value, 16 for values from 0 through 10 inclusive, and 1 for the remaining values.

18_switch_dispatch.zp64
const c64 = @import("c64");

const commands = [_]u8{ c64.key.return_, c64.key.cursor_down, c64.key.space, 99 };

fn dispatch(code: u8) u8 {
    return switch (code) {
        c64.key.return_ => 1,
        c64.key.cursor_down, c64.key.cursor_up => 2,
        c64.key.space => 32,
        else => 4,
    };
}

fn wordDispatch(value: u8) u16 {
    return switch (value) {
        39 => 512,
        0...10 => 16,
        else => 1,
    };
}

export fn main() void {
    c64.console.clear();
    c64.console.print("switch dispatch\n", .{});

    var sum: u8 = 0;
    for (commands) |command| {
        sum += dispatch(command);
    }

    const word = wordDispatch(sum);
    c64.console.print("dispatch {x}\n", .{sum});
    c64.console.print("word {x16}\n", .{word});

    switch (sum) {
        39 => {
            c64.console.print("switch ok\n", .{});
            c64.vic.border = 5;
        },
        else => {
            c64.console.print("switch bad\n", .{});
            c64.vic.border = 2;
        },
    }
}

Open the complete source

Expect DISPATCH 27, WORD 0200, and SWITCH OK. The first two lines use hex. A comma list shares one branch body, while an unsigned range covers every selector value between its endpoints. Overlapping labels and ranges are rejected. The final switch is a statement and performs output and I/O in its branches.

Byte, word, Boolean, and signed equality cases · Rejected overlapping alternatives

Enums, optionals, and tagged unions

An enum(u8) has byte tags. A scalar optional stores presence and payload. A supported pointer optional uses address zero for null. Narrow tagged unions select a payload through a switch capture. This demo models a small event instead of passing a tag and value separately.

24_optional_union_event.zp64
const c64 = @import("c64");

const Cell = enum(u8) { empty, x, o };
const Event = union(enum) { none, key: u8, cell: Cell };

fn eventFromKey(key: u8) Event {
    if (key == '1') {
        return Event{ .cell = .x };
    }
    if (key == '2') {
        return Event{ .cell = .o };
    }
    if (key == c64.key.return_) {
        return Event{ .key = key };
    }
    return Event{ .none = {} };
}

fn cellFromEvent(event: Event) ?Cell {
    switch (event) {
        .cell => |cell| {
            return cell;
        },
        else => {
            return null;
        },
    }
}

fn eventCode(event: Event) u8 {
    return switch (event) {
        .none => 0,
        .key => |key| key,
        .cell => |cell| switch (cell) {
            .x => 1,
            .o => 2,
            else => 9,
        },
    };
}

export fn main() void {
    c64.console.clear();
    c64.console.print("optional union event\n", .{});

    const first = eventFromKey(c64.keyboard.waitPetscii());
    const second = eventFromKey(c64.keyboard.waitPetscii());
    const maybe_cell = cellFromEvent(first);
    var result: u8 = eventCode(first) + eventCode(second);

    if (maybe_cell) |cell| {
        result += switch (cell) {
            .x => 20,
            .o => 30,
            else => 0,
        };
    } else {
        result += 40;
    }

    c64.console.print("result {x}\n", .{result});
    if (result == 23) {
        c64.console.print("union optional ok\n", .{});
        c64.vic.border = 5;
    } else {
        c64.console.print("union optional bad\n", .{});
        c64.vic.border = 2;
    }
}

Use a fixed table and guard a runtime lookup

Use [_]u8 when the initializer determines the length. A declaration such as var bytes: [4]u8 = .{ 1, 2, 3, 4 }; gives the initializer its type from the binding. Both allocate four contiguous bytes. A word table with four entries needs eight bytes. .len counts elements, so the same bounds check applies to either table.

Fixed lookup with an early return
const tile_colors = [_]u8{ 0, 5, 7, 2 };

fn colorFor(tile: u8) u8 {
    if (tile >= tile_colors.len) {
        return 0;
    }
    return tile_colors[tile];
}

For tile 2 the function returns 7. For tile 4 it returns the fallback before touching the table. A runtime index has no automatic bounds check. A function can return from within a loop or an if. Use break when only the loop should end, and return when the caller should get control back. A discard such as _ = step(); still runs step and keeps its effects.

Fixed tables, mutable arrays, and element operations · Early return and discarded-call effects · Break and continue on screen

Share code and tables within one program

Put reusable declarations in a local source file and use its import alias from the caller. The compiler can include read-only tables from an imported file and refer to them through the same alias. These tables are built into the program, so they have no loader or disk lifecycle. If the feature instead needs its own load window and export ABI, use the module chapter.

Asset file

Read-only palette
const title = "RODATA ASSET";
const values = [_]u8{ 2, 3, 5 };

Caller

Read a palette entry
const c64 = @import("c64");
const assets = @import("29_module_rodata_assets_data.zp64");

export fn main() void {
    c64.console.clear();
    c64.console.print("RODATA MODULE\n", .{});

    var border: u8 = assets.values[2];
    if (border == 5) {
        c64.console.print("ASSET OK\n", .{});
        c64.vic.border = border;
    } else {
        c64.console.print("ASSET BAD\n", .{});
        c64.vic.border = 2;
    }
}

Open the complete source

Read-only import fixture · Runnable read-only import demo · DLL walkthrough

Use a layout calculation in code that runs on the C64

The compiler resolves layout queries against the C64 representation. Header is five bytes with alignment one, so the array has six bytes. The Boolean field ok has offset four, which selects the value 4 from that array.

record-layout.zp64
const c64 = @import("c64");

const Cell = enum(u8) { empty, x, o };
const Header = struct { tag: u8, word: u16, cell: Cell, ok: bool };
const Nested = struct { prefix: u8, header: Header };

fn headerSize() usize {
    return @sizeOf(Header);
}

export fn main() void {
    var bytes: [@sizeOf(Header) + @alignOf(Header)]u8 = .{ 0, 1, 2, 3, 4, 5 };
    const flag_byte: u8 = bytes[@offsetOf(Header, "ok")];
    const size = headerSize();
    const nested_offset: usize = @offsetOf(Nested, "header.word");

    c64.console.clear();
    c64.console.print("SIZE {x16} FLAG {x}\n", .{ size, flag_byte });
    c64.console.print("NESTED OFFSET {x16}\n", .{nested_offset});
}

Open the complete source

Expect SIZE 0005 FLAG 04 and NESTED OFFSET 0002. The compiler resolves @sizeOf even when it appears inside a normal runtime function. For a fixed array length, put the query and supported arithmetic directly in the length. General comptime blocks and arbitrary calls in array lengths are outside the subset. Calculate the offsets by hand.

Syntax and target limits

Zig's AST validates ordinary syntax before ZeroPage lowers its target subset. ZeroPage adds machine declarations and asm { ... }. It gives callconv and linksection target-specific meanings. Valid Zig can receive a ZeroPage diagnostic for constructs such as slices, floating point, division, generics, error unions, or general comptime.

Language reference · Pinned Zig behavior