Learn ZeroPage

Start with a small C64 program. Build an interactive sector survey, give its records a place to live, and load new rules from disk.

Start chapter 1Install and build

Jump to an overview topic

Start with the C64 programming model

ZeroPage is a language for writing native Commodore 64 programs. Write functions, records, and control flow in a Zig-shaped source file. The compiler emits 6502 assembly, and 64tass turns it into a PRG. The program runs on the C64 and contains the runtime helpers it uses.

When you need toUseWhat you decide
Keep and update a valueTyped locals and recordsChoose a byte or a word and who can modify it.
Reach the machineC64 helpers, volatile pointers, or inline assemblyChoose the device operation and which effects must survive the call.
Make room for dataNamed RAM regions, arenas, and REU viewsChoose who owns the bytes, when to reuse them, and what to transfer.
Make room for codePlaced resident code or disk-loaded DLLsChoose where code runs and when it becomes available.

Start with the first program below. Then build a small sector survey. First it tracks a selection and a visit count on the C64. Later exercises encode a sector record, move a larger table into an REU, and show how a separate disk payload supplies code. Each step starts with a result you can check on screen or in the emulator.

Zig supplies the parser for ordinary source syntax. ZeroPage supports a target-specific subset and adds declarations for the machine. The language chapter explains where that boundary matters. You can read the tutorial before installing anything. Use Setup when you want to build the first PRG.

Read your first program

The compiler starts at export fn main() void. The c64 import provides the machine-facing API. .{} is an empty argument tuple for the formatter.

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

export fn main() void {
    c64.console.clear();
    c64.console.print("HELLO FROM ZEROPAGE\n", .{});
    c64.vic.border = 5;
}

The default image loads at $0801. A BASIC line runs SYS 2061, entering the compiled program at $080d. Expect a greeting and a green border. On hardware, put the PRG on a disk or compatible storage device, load it, and enter RUN.

Write typed 6510 code

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

Model a small piece of game state

Start by grouping values that change together. A game can keep its cursor position, hit points, and facing in one record. A function that takes the record by value gets a copy. A function that takes its address can update the caller's record. Pick the first when you want an independent snapshot and the second when you want one live game state.

A position and a move · excerpt
const Position = struct { x: u8, y: u8 };

fn moveRight(pos: *Position) void {
    if (pos.x < 39) {
        pos.x += 1;
    }
}

The right edge of the default 40-column screen is column 39. Starting at 38, the first call advances the original position to 39. A second call leaves it there. The record chapter compares this style with returning a new value and explains what happens when a copied field is itself a pointer.

Talk to the hardware

The border helper maps to the VIC-II register at $d020. The example below uses a volatile pointer to that register, then an assembly block to write the background register at $d021. Build docs/tutorial-examples/volatile-border.zp64 using the same command pattern.

volatile-border.zp64
export fn main() void {
    const border: *volatile u8 = @ptrFromInt(0xd020);
    border.* = 5;
    asm {
        lda #$06
        sta $d021
    }
}

Use c64.screen for direct screen writes, c64.console for PETSCII output and formatting, and c64.kernal when you need the ROM routines. The keyboard API reports PETSCII values. Inline assembly has a documented instruction and operand subset. C64 API · Inline assembly rules

Use assembly for one machine operation

Keep the application in ZeroPage and use a small assembly block where it helps express the machine operation. Here, @color names a mutable source byte. The block counts three iterations in X and writes the resulting value to the VIC-II border register.

asm-border.zp64
const c64 = @import("c64");

export fn main() void {
    c64.console.clear();
    var color: u8 = 2;
    asm {
        ldx #3
    brighten:
        inc @color
        dex
        bne brighten
        lda @color
        sta $d020
    }
    c64.console.print("BORDER {x}\n", .{color});
}

Expect BORDER 05. The wrapper restores A, X, and status. The changes to color and the VIC-II register remain. When a firmware routine returns a register value, save it to a source variable inside the block before the wrapper restores the register. The assembly chapter takes this further with record fields, string addresses, and KERNAL calls.

Plan the memory layout

Open the memory placement demo. It declares visible code at $2000, an arena at $9000, and a region at $e000 behind KERNAL ROM. The resident image starts from its configured entry at $1000.

95_memory_regions_placement.zp64 · placement excerpt
const c64 = @import("c64");

const hidden_values linksection("hidden") = [_]u8{ 0x21, 0x42, 0x63 };

memory {
    region direct_code: c64 at 0x2000 size 0x0100;
    region near_arena: c64 at 0x9000 size 0x0100;
    region hidden_code: c64 at 0xe000 size 0x0100 bank .ram_under_kernal;

    placement direct in direct_code;
    placement hidden in hidden_code load .startup_copy;
    arena near_heap in near_arena;

    image prg {
        load_addr = 0x0801;
        entry_addr = 0x1000;
        basic_stub = true;
        address_limit = 0xc600;
    }
}

fn directAdd(value: u8) linksection("direct") u8 {
    return value + 1;
}

fn hiddenLookup(index: u8) linksection("hidden") u8 {
    return hidden_values[index];
}

linksection("hidden") places the lookup function and table together. .startup_copy keeps their bytes in the load image and copies them to the run address before main. A resident call gateway exposes the hidden RAM and restores the previous mapping. The demo also uses near_heap.allocBytes(2), which returns an optional pointer to visible C64 RAM.

Expect PLACEMENT ARENA OK. Open build/placement.prg.zpmap.json and compare the load and run addresses of the hidden placement. A named pool allocates equal-sized blocks, while an arena releases its allocations together with reset(). The separate zero_page policy governs borrowed bytes and fixed reservations. Region ownership and zero-page policy

Give temporary data a lifetime

Suppose your game needs a scratch buffer only while drawing a frame. Name a C64 RAM region and assign it to an arena. Check the optional allocation before using it. When the frame is finished, reset the arena so the next frame can reuse the same space.

34_near_heap_arena.zp64
const c64 = @import("c64");

memory {
    region main_ram: c64 at 0x9000 size 0x0100;

    arena near_heap in main_ram;
}

export fn main() void {
    c64.console.clear();
    c64.console.print("NEAR HEAP ARENA\n", .{});

    const first = near_heap.allocBytes(8);
    if (first) |first_buf| {
        first_buf[0] = 0x48;
        first_buf[1] = 0x50;
        if (first_buf[0] == 0x48 and first_buf[1] == 0x50) {
            c64.console.print("ALLOC OK\n", .{});
        }
    }

    near_heap.reset();
    const again = near_heap.allocBytes(1);
    if (again) |again_buf| {
        if (@intFromPtr(again_buf) == 0x9000) {
            c64.console.print("RESET OK\n", .{});
            c64.vic.border = 5;
        }
    }
}

Expect ALLOC OK and RESET OK. Every pointer from the old allocation becomes stale at reset. Use a fixed-block pool instead when objects have independent lifetimes and need to be returned one at a time. The arena chapter compares those lifetimes and shows how to store a record in allocated bytes.

Edit records stored in REU

The CPU can directly address C64 RAM. To use bytes in an REU, copy them into C64 RAM over DMA. A far arena allocates REU storage, and a typed view gives you record-sized reads and writes. If you will edit several fields repeatedly, materialize a range into a near arena, work on it there, then flush it back.

  1. Allocate and initialize the far records. In the map example, forty eight-byte sectors take 320 bytes in REU.
  2. Bring four sectors into a 32-byte near arena. Far sector 36 becomes local sector 0 in a range starting at 36.
  3. Edit the local records, flush back to far index 36, then reset the near arena. Check the result with a new far read.

Continue with the guided REU exercise and try a request that crosses the end of the map. Then update 200 enemies in batches of 20. Use the capacity table to choose an emulator or hardware layout before starting transfers.

Call code loaded from disk

A DLL gives you a way to bring in code as well as data. The compiler fixes the export signature and the location of each export in the jump table. At runtime, KERNAL reads a disk payload into staging RAM, the loader keeps a copy in REU, and the CPU executes the relocated code in a C64 RAM window.

Start with the side-by-side disk example. The named version supplies the module and export names at the call site. The typed version declares the signature once and uses ordinary call arguments. Both return an optional because the loader may be unable to make the export available.

Continue with the shared execution window to follow the REU cache, or the score updater to see a disk DLL, a far arena, and a near working copy in one program.

Check the result on the target

Start with what the program should do. Observe the screen or border for a device write, or look at the destination bytes in the VICE monitor for a copy. Read the compiler's assembly when you need to see the instructions and its map when you need to see which code or data owns an address.

For the placement example above, check both the load and run address of the hidden table. For the disk example, check that the disk contains the payload under the declared name. The verification chapter connects each question to a compiler artifact or an emulator observation.

Continue into the full guide

Work through the tutorial chapters in order or start with the complete game walkthrough to see how the language fits a real application. The full guide covers specific language features, APIs, and machine contracts in more detail.

Start the first chapter Browse the full guide