Getting started

Install the compiler

On Linux:

curl -fsSL https://alloylang.org/install.sh | sh

On Windows, in PowerShell:

irm https://alloylang.org/install.ps1 | iex

Then open a new terminal and check it:

alloyc --version

A first program

Save this as hello.alloy:

import std::io;

fn main() {
    print_line(&"Hello from Alloy");
}

alloyc run hello.alloy runs it at once, interpreted. alloyc build hello.alloy makes an executable, hello (hello.exe on Windows), checked: a bug faults with its file and line. Add --release for an optimized one, and --target windows-x86_64, linux-aarch64 or web-wasm32 to build for another platform from any of them.

Nothing is in scope until imported: std::io gives print_line. A & before an argument says it is borrowed; the specification tells why every borrow, move and copy is written.

A window and a UI

The UI packages live in the package registry. In a new folder, save this as counter.alloy:

import std::string;
import pkg::alloy::window;
import pkg::alloy::ui;

// A count shown in a text a binding remakes when it changes, and buttons
// changing it.
fn counter(ui: &var Ui) -> Element {
    const count = ui.signal(0);
    return ui.add(Column {
        .gap = 12.0,
        .padding = Padding::all(24.0),
        .children = &[
            ui.bind((ui) => Text::from(f"Clicked {count.get(&ui)} times")),
            ui.add(Row {
                .gap = 8.0,
                .children = &[
                    ui.add(Button {
                        .label = String::from(&"Add one"),
                        .variant = ButtonVariant::Primary,
                        .on_press = (ui) => count.update(&var ui, (n) => n += 1),
                    }),
                    ui.add(Button::text(&"Reset", (ui) => count.set(&var ui, 0))),
                ],
            }),
        ],
    });
}

fn main() -> i32 {
    var config = WindowConfig::titled(&"Counter");
    config.size = Size { .width = 360, .height = 160 };
    return app(&config, counter);
}

Then fetch what it imports: pkg::alloy::ui and pkg::alloy::window, and the packages they need (draw, text, gpu, ...), into the folder's pkg/:

alloyc get counter.alloy

Commit pkg/ with your code: it is the record of the packages and versions the program uses, and building needs no network. alloyc update moves them to newer releases later, and alloyc get alloy::ui_controls adds one by name.

A Ui holds the elements; ui.signal(0) is a value the UI shows, and ui.bind remakes the text whenever the count it reads changes. Build and run it:

alloyc build counter.alloy
./counter

On Windows, .\counter.exe.

Your own loop

A game draws every frame itself. pkg::alloy::window gives the window and its events, pkg::alloy::gpu the device to draw with: Vulkan on Linux and Windows, Metal on macOS, WebGPU in a browser. In another folder, save this as frame.alloy:

import std::io;
import std::string;
import std::option;
import std::time;
import std::math;
import pkg::alloy::window;
import pkg::alloy::gpu;

// The device to draw with and the window's surface, made once the window
// is shown.
type Gpu = struct {
    device: Device,
    surface: Surface
};

// What the game keeps between events.
type Game = struct {
    gpu: Option<Gpu>,
    start: Instant,
};

// Called by `run` for every event of the window.
fn on_event(game: &var Game, window: &var Window, event: &Event) {
    match (event) {
        ::Redraw {
            if (game.gpu is ::None) {
                game.gpu = window.open();
            }

            if (game.gpu is ::Some |&var gpu|) {
                gpu.frame(game.start.elapsed().seconds() to f32, &var window);
                // the next frame at once: the loop runs at the display's rate
                window.request_redraw();
            } else {
                // no device or no surface: nothing to draw with
                window.close();
            }
        }
        ::Key |&k| {
            if (k.pressed && k.key is ::Escape) {
                window.close();
            }
        }
        ::CloseRequested {
            window.close();
        }
    }
}

// An extension on `Window` (its first parameter is `self`), called as
// `window.open()`: the device and the window's surface, or None.
fn open(self window: &Window) -> Option<Gpu> {
    var device = if (Device::open(Backend::Automatic) is ::Ok |move d|) move d else {
        print_error(&"no device to draw with\n");
        return ::None;
    };

    const surface = if (device.surface(&window) is ::Ok |s|) s else {
        print_error(&"no surface for the window\n");
        return ::None;
    };

    print_line(&f"drawing on {device.name()}".view());
    return ::Some(Gpu { .device = move device, .surface = surface });
}

// An extension on `Gpu`, called as `gpu.frame(...)`: one frame, the window
// cleared to a color changing with the time.
fn frame(self gpu: &var Gpu, seconds: f32, window: &var Window) {
    const target = if (gpu.device.acquire(gpu.surface, window.size()) is ::Some |t|) t else {
        return; // the window has no area
    };

    const color = Color::rgb(0.5 + 0.5 * sin(seconds), 0.3, 0.5 + 0.5 * cos(seconds));

    var encoder = Encoder::empty();
    encoder.begin_render_pass(target, ::Some(color));
    encoder.end_render_pass();

    gpu.device.submit(move encoder);
    gpu.device.present(gpu.surface, &var window);
}

fn main() -> i32 {
    var game = Game { .gpu = ::None, .start = Instant::now() };
    // `on_event` is a plain function, since `run` takes it as a value
    return run(&WindowConfig::titled(&"Frames"), move game, on_event);
}

run keeps the program's state, here a Game, and calls on_event with it for every event. Each Redraw draws one frame and asks for the next, so the loop runs at the display's rate; Escape or closing the window ends it.

open and frame are extensions: a function whose first parameter is marked self is called on that parameter, window.open() and gpu.frame(...), and only that way. on_event stays a plain function, since run takes it as a value.

Fetch the two packages, then build and run it as before:

alloyc get frame.alloy
alloyc build frame.alloy
./frame

Pipelines, shaders in WGSL, buffers and textures are in pkg::alloy::gpu's documentation.

A UI over your loop

A Hud from pkg::alloy::ui draws a UI over the game's frame, on the game's device, without taking its loop. The loop above with a HUD counting clicks, saved as hud.alloy:

import std::io;
import std::string;
import std::option;
import std::time;
import std::math;
import pkg::alloy::window;
import pkg::alloy::gpu;
import pkg::alloy::ui;

// The device to draw with and the window's surface, made once the window
// is shown.
type Gpu = struct {
    device: Device,
    surface: Surface
};

// What the game keeps between events, the HUD among it once there is a
// device to draw it with.
type Game = struct {
    gpu: Option<Gpu>,
    hud: Option<Hud>,
    start: Instant,
};

// The HUD's view, a UI like the counter's: made once, its text kept up
// to date by the signal it reads.
fn hud(ui: &var Ui) -> Element {
    const clicks = ui.signal(0);
    return ui.add(Column {
        .gap = 8.0,
        .padding = Padding::all(16.0),
        .children = &[
            ui.bind((ui) => Text::from(f"Clicked {clicks.get(&ui)} times")),
            ui.add(Row {
                .gap = 8.0,
                .children = &[
                    ui.add(Button::text(&"Click", (ui) => clicks.update(&var ui, (n) => n += 1))),
                    ui.add(Button::text(&"Quit", (ui) => ui.quit())),
                ],
            }),
        ],
    });
}

// Called by `run` for every event of the window, the HUD seeing it first.
fn on_event(game: &var Game, window: &var Window, event: &Event) {
    if (game.hud is ::Some |&var hud| && hud.event(&var window, &event)) {
        return; // the HUD took it: a click on one of its buttons
    }

    match (event) {
        ::Redraw {
            if (game.gpu is ::None) {
                game.gpu = window.open();
                if (game.gpu is ::Some |&var gpu|) {
                    // drawn on the game's device into frames of its surface
                    const format = gpu.surface.format;
                    game.hud = ::Some(Hud::create(&var gpu.device, format, &window, hud));
                }
            }

            if (game.gpu is ::Some |&var gpu| && game.hud is ::Some |&var hud|) {
                gpu.frame(game.start.elapsed().seconds() to f32, &var hud, &var window);
                window.request_redraw();
            } else {
                window.close();
            }
        }
        ::Key |&k| {
            if (k.pressed && k.key is ::Escape) {
                window.close();
            }
        }
        ::CloseRequested {
            window.close();
        }
    }
}

// The device and the window's surface, or None.
fn open(self window: &Window) -> Option<Gpu> {
    var device = if (Device::open(Backend::Automatic) is ::Ok |move d|) move d else {
        print_error(&"no device to draw with\n");
        return ::None;
    };

    const surface = if (device.surface(&window) is ::Ok |s|) s else {
        print_error(&"no surface for the window\n");
        return ::None;
    };

    return ::Some(Gpu { .device = move device, .surface = surface });
}

// One frame: the game's drawing, then the HUD over it.
fn frame(self gpu: &var Gpu, seconds: f32, hud: &var Hud, window: &var Window) {
    const target = if (gpu.device.acquire(gpu.surface, window.size()) is ::Some |t|) t else {
        return;
    };

    const color = Color::rgb(0.5 + 0.5 * sin(seconds), 0.3, 0.5 + 0.5 * cos(seconds));

    var encoder = Encoder::empty();
    encoder.begin_render_pass(target, ::Some(color));
    encoder.end_render_pass();

    // what changed in the HUD drawn again, then blended over the frame
    hud.draw(&var gpu.device, &var encoder, target, &var window);

    gpu.device.submit(move encoder);
    gpu.device.present(gpu.surface, &var window);
}

fn main() -> i32 {
    var game = Game { .gpu = ::None, .hud = ::None, .start = Instant::now() };
    return run(&WindowConfig::titled(&"Frames"), move game, on_event);
}

Three calls: Hud::create once there is a device, hud.event for every event, which says whether the HUD took it (a click on a button, a key in a text field) so the game leaves it, and hud.draw after the game's drawing. The HUD keeps its drawing in a texture and redraws only what changed, so a still HUD costs one blended image a frame. It gives the window the cursor, the input method and the clipboard, and ui.quit() closes it. Its background work (ui.background) runs at once on the loop's thread, unless the game hands it workers: Workers::run around the loop and hud.with_workers(&workers).

alloyc get hud.alloy
alloyc build hud.alloy
./hud

Next