Live reload

Every earlier tutorial’s source banner had two run modes:

  • daslang.exe <script> — standalone; runs main() which loops init / update / shutdown until exit_requested().

  • daslang-live <script> — same script, hosted inside a wrapper process that watches the file, reruns the typer on save, and swaps the new program in without restarting the GLFW window. ImGui context, registered widget state, dock layout, slider values — anything @live or restored via a hook — carry across the reload.

This tutorial walks through the seams the live-reload framework exposes:

  • live_create_window / live_imgui_init — idempotent so they no-op on reload (the preserved ImGui context is reused).

  • live_begin_frame / live_end_frame — per-frame gate / commit. live_begin_frame returns false while the host is paused or in the middle of swapping programs; skip the frame.

  • @live annotation — preserves a global (or struct field) across reload via auto-generated [before_reload] / [after_reload] serializers in the live/live_vars module.

  • [live_command] — registers an HTTP endpoint that the running process exposes; called from curl or any other client. The imgui_force_set / imgui_click / imgui_snapshot surface is built from [live_command] declarations.

  • [before_reload] / [after_reload] — manual save/restore hooks for state @live can’t track (raw pointers, GL textures, C-owned resources).

Source: examples/tutorial/live_reload.das.

Walkthrough

The recording can’t trigger a reload, so it exercises the observable surface and asserts each piece: it force-sets the @live VOLUME slider and verifies the value (force_set_verified), clicks the @live PING_BTN twice and verifies click_count (hold_through_voice), then calls the user-defined bump_counter and reset_counter [live_command] endpoints from outside and verifies the counter climbs to 7 and back to 0 (record_check_value on the snapshot readout). A command that stopped reaching the running program would abort the recording.

  1options gen2
  2
  3require imgui
  4require imgui_app
  5require opengl/opengl_boost
  6require live/glfw_live
  7require live/live_api
  8require live/live_commands
  9require live/live_vars
 10require live_host
 11require imgui/imgui_live
 12require imgui/imgui_boost_runtime
 13require imgui/imgui_boost_v2
 14require imgui/imgui_widgets_builtin
 15require imgui/imgui_containers_builtin
 16require imgui/imgui_visual_aids
 17require daslib/json public
 18require daslib/json_boost public
 19
 20// =============================================================================
 21// TUTORIAL: live_reload — the daslang-live workflow that every earlier
 22// tutorial implicitly relied on.
 23//
 24// Every tutorial's STANDALONE / LIVE blocks pointed at the same shape:
 25//
 26//   STANDALONE: daslang.exe <script>
 27//   LIVE:       daslang-live <script>
 28//
 29// In the live mode, the script is hosted inside daslang-live: a wrapper
 30// process that runs your `init` / `update` / `shutdown` exports, watches
 31// the source file for edits, and exposes an HTTP server for `imgui_force_set` /
 32// `imgui_click` / `imgui_snapshot` and any user-defined `[live_command]`.
 33// Save the file and daslang-live re-runs the typer/codegen, calls
 34// `[before_reload]` hooks to stash anything that needs surviving, swaps in
 35// the new program, then calls `[after_reload]` to restore. The GLFW
 36// window stays open; the ImGui context, registered widget state, dock
 37// layout, slider values — anything @live or restored via a hook — all
 38// carry across the gap.
 39//
 40// This tutorial demonstrates each piece:
 41//
 42//   1. `live_create_window` / `live_imgui_init` — idempotent, reload-safe
 43//   2. `live_begin_frame()` — per-frame gate; returns false while paused
 44//                              or reloading. Skip the frame if it does.
 45//   3. `@live` on a state struct — value preserved across reload
 46//   4. `[live_command]` — custom HTTP endpoint that the running process
 47//                          exposes; driven from curl just like imgui_force_set
 48//   5. `[before_reload]` / `[after_reload]` — explicit save/restore hooks
 49//                                              for state the framework
 50//                                              doesn't track automatically
 51//
 52// STANDALONE: daslang.exe modules/dasImgui/examples/tutorial/live_reload.das
 53// LIVE:       daslang-live modules/dasImgui/examples/tutorial/live_reload.das
 54//
 55// DRIVE (when running live):
 56//   curl -X POST -d '{"name":"imgui_snapshot"}'                                                       localhost:9090/command
 57//   curl -X POST -d '{"name":"bump_counter"}'                                                          localhost:9090/command
 58//   curl -X POST -d '{"name":"reset_counter"}'                                                         localhost:9090/command
 59//   curl -X POST                                                                                       localhost:9090/reload
 60// =============================================================================
 61
 62// ---- Custom counter that survives reload via @live ----
 63// Plain module-scope var, marked @live so daslang-live's serializer hauls
 64// it across the reload boundary. Non-`@live` globals reinitialise on
 65// reload — see the demo_string field below for that contrast.
 66var private @live g_custom_counter : int = 0
 67// NOT @live — gets reset on each reload (intentional for the demo).
 68var private g_session_string : string = "fresh session"
 69
 70// ---- Custom live_command — externally callable HTTP endpoint ----
 71// imgui_force_set / imgui_click / imgui_snapshot are all `[live_command]`
 72// internally. Users can add their own:
 73struct BumpArgs {
 74    @optional by : int = 1
 75}
 76
 77[live_command(description = "Bump the custom counter by N (default 1).")]
 78def bump_counter(input : JsonValue?) : JsonValue? {
 79    let args = from_JV(input, type<BumpArgs>)
 80    g_custom_counter += args.by
 81    return JV((ok = true, counter = g_custom_counter))
 82}
 83
 84[live_command(description = "Reset the custom counter to 0.")]
 85def reset_counter(_input : JsonValue?) : JsonValue? {
 86    g_custom_counter = 0
 87    return JV((ok = true, counter = 0))
 88}
 89
 90// ---- Reload hooks — fire on reload boundary ----
 91// [before_reload] runs in the OLD program after the file edit is detected
 92// but before the new program loads. Use it to stash non-`@live` data that
 93// the new program will pick up in `[after_reload]`. Frequently it's
 94// enough to mark the relevant var `@live` instead, but hooks are the
 95// escape hatch when serialization isn't possible (raw pointers, file
 96// handles, GL textures...).
 97[before_reload]
 98def private on_before_reload() {
 99    print("[live_reload tutorial] before_reload fired. g_custom_counter = {g_custom_counter}\n")
100}
101
102[after_reload]
103def private on_after_reload() {
104    print("[live_reload tutorial] after_reload fired. g_custom_counter = {g_custom_counter} (preserved by @live)\n")
105}
106
107[export]
108def init() {
109    // Both functions are idempotent on reload — cold start creates the
110    // window + ImGui context, reload re-uses the preserved ImGui context
111    // and skips the duplicate CreateContext call (see live_imgui_init
112    // body in imgui_live.das).
113    live_create_window("dasImgui live_reload tutorial", 1040, 720)
114    live_imgui_init(live_window)
115    DisableIniPersistence()
116    let io & = unsafe(GetIO())
117    GetStyle().FontScaleMain = 1.5
118
119    // Re-running init resets g_session_string each reload. (Initial-value
120    // assignments at module scope run once at program load, but `init` is
121    // called both on cold-start AND on reload.)
122    g_session_string = "fresh session"
123}
124
125[export]
126def update() {
127    // The frame-gate. Returns false while daslang-live is paused, in the
128    // middle of swapping programs, or in any other state where rendering
129    // would crash or produce garbage. Always early-out on false.
130    if (!live_begin_frame()) return
131
132    begin_frame()
133
134    ImGui_ImplGlfw_NewFrame()
135    apply_synth_io_override()
136    NewFrame()
137
138    SetNextWindowPos(ImVec2(30.0f, 30.0f), ImGuiCond.FirstUseEver)
139    SetNextWindowSize(ImVec2(640.0f, 460.0f), ImGuiCond.FirstUseEver)
140    window(LIVE_WIN, (text = "live_reload", closable = false,
141                      flags = ImGuiWindowFlags.None)) {
142
143        // ---- A slider whose value survives reload (@live in SliderStateFloat) ----
144        text("VOLUME.value is @live - survives reload.")
145        slider_float(VOLUME, (text = "Volume"))
146
147        separator(LR_SEP_1)
148
149        // ---- The custom counter, driven from outside via [live_command] ----
150        // Mirror the @live counter into a text_show so the snapshot can address
151        // it (the recording asserts the [live_command]s moved it). g_custom_counter
152        // is still the plain @live var; this is just the readout.
153        CTR_TEXT.value := "g_custom_counter = {g_custom_counter}"
154        text_show(CTR_TEXT)
155        text("  - @live, preserved across reload")
156        text("  - mutated externally by `bump_counter` / `reset_counter`")
157
158        separator(LR_SEP_2)
159
160        // ---- Contrast: session string resets each reload ----
161        text("g_session_string = \"{g_session_string}\"")
162        text("  - NOT @live; init() rewrites it each reload")
163
164        separator(LR_SEP_3)
165
166        // ---- A button whose click count is preserved (ClickState is @live) ----
167        if (button(PING_BTN, (text = "Ping (click_count survives reload)"))) {}
168        text("PING_BTN.click_count = {PING_BTN.click_count}")
169    }
170
171    end_of_frame()
172    Render()
173    var w, h : int
174    live_get_framebuffer_size(w, h)
175    glViewport(0, 0, w, h)
176    glClearColor(0.10f, 0.10f, 0.12f, 1.0f)
177    glClear(GL_COLOR_BUFFER_BIT)
178    live_imgui_render()
179
180    // Always match live_begin_frame with live_end_frame to keep the
181    // frame pump alive on the daslang-live side.
182    live_end_frame()
183}
184
185[export]
186def shutdown() {
187    // Idempotent on reload - live_imgui_shutdown skips during reload so
188    // the ImGui context is preserved; only the cold process exit runs
189    // the full teardown.
190    live_imgui_shutdown()
191    live_destroy_window()
192}
193
194[export]
195def main() {
196    // Standalone entrypoint. daslang-live drives init/update/shutdown
197    // directly and ignores main(); plain `daslang.exe <file>` runs this
198    // loop.
199    init()
200    while (!exit_requested()) {
201        update()
202    }
203    shutdown()
204}

The reload boundary

A daslang-live reload runs in this order:

  1. File watcher notices a source-tree edit (or an HTTP POST /reload request arrives).

  2. The HOST collects every [before_reload] function and runs them in the OLD program. The live/live_vars module auto-generates one of these per @live global; the user can register more.

  3. Typer + codegen run against the new source. If they fail, the reload aborts and the old program keeps running — live_get_error surfaces the diagnostic.

  4. The new program is loaded. [after_reload] hooks run, restoring the saved state (@live first, then user hooks).

  5. The next update() call sees live_begin_frame() == true and normal rendering resumes.

The GLFW window and the OS-level ImGui context survive the swap — only the daslang program is replaced.

@live preservation

The simplest way to keep a value across reload is the @live annotation on the global (or on individual struct fields). The live/live_vars module synthesizes the matching save/restore hooks at compile time:

var private @live g_custom_counter : int = 0

The serializer uses daslib/archive; primitives, arrays, tables, strings, and any struct whose fields are themselves @live-friendly all work out of the box. Each @live target gets its own storage key, and the saved data carries a hash of the initialization expression — change the initializer in source, and the stale value is discarded automatically. (No “I changed the default to 10 and now my old value of 0 is wrong” foot-gun.)

Boost widget state types (ClickState, SliderStateFloat, ToggleState, WindowState, …) are already structured this way — their value-carrying fields are @live, their pending-flags fields are not. That’s why a slider’s value survives reload but pending_value doesn’t.

The frame gate

live_begin_frame() is the only way the host signals “do not render this frame”:

def update() {
    if (!live_begin_frame()) return
    // ... NewFrame, your draw calls, Render
    live_end_frame()
}

States that return false:

  • The host is paused (POST /pause from daslang-live or mcp__daslang__live_pause).

  • A reload is in progress (between [before_reload] and [after_reload]).

  • The most recent typer pass failed and the program is “frozen” on the prior version — the next save that compiles will revive it.

Always early-out on false and always pair with live_end_frame() on the success branch.

[live_command] — user-defined HTTP endpoints

The same [live_command] annotation that registers imgui_force_set / imgui_click / imgui_snapshot works for user functions. The function takes a JsonValue? (the request body’s args field) and returns JsonValue? (echoed back to the caller):

struct BumpArgs {
    @optional by : int = 1
}

[live_command(description = "Bump the custom counter by N (default 1).")]
def bump_counter(input : JsonValue?) : JsonValue? {
    let args = from_JV(input, type<BumpArgs>)
    g_custom_counter += args.by
    return JV((ok = true, counter = g_custom_counter))
}

The endpoint name (bump_counter) is the function name; the HTTP surface routes POST /command requests with {"name":"bump_counter"} to this handler. The handler runs on the GLFW main thread between frames, so it can safely touch daslang globals and ImGui state without locks.

Manual reload hooks

When @live doesn’t fit — typically because the state is a pointer to a C-owned resource that the new program won’t recognize — declare a pair of hooks explicitly:

[before_reload]
def private on_before_reload() {
    // Stash whatever ``@live`` can't serialize.
    // live_store_bytes / live_store_string store under a string key.
}

[after_reload]
def private on_after_reload() {
    // Re-read the stash and rebuild the in-memory state.
    // live_load_bytes / live_load_string read by the same key.
}

imgui_live.das itself is the canonical example: it serializes the live_imgui_ctx pointer as a uint64 in [before_reload] and re-binds it with SetCurrentContext in [after_reload].

Init / shutdown idempotence

init runs on both cold-start AND reload. shutdown runs on reload AND process exit. The framework helpers (live_imgui_init / live_imgui_shutdown) are idempotent — they detect the reload case and no-op accordingly — so the script’s init / shutdown exports can be written once without distinguishing cold-start from reload.

User globals initialized at module scope (var x = 0) only run their initializer once at program load — reload starts a NEW program, so that initializer runs again. Use @live (or a [before_reload] hook) for anything you want to preserve. Anything reset INSIDE init rebuilds each reload — the demo’s g_session_string shows that pattern.

Standalone vs live

Run standalone with daslang.exe — every part of this tutorial still works EXCEPT the [live_command] HTTP endpoints, which need the daslang-live host. The reload hooks are silent in standalone mode (they only fire on the reload boundary, which never happens).

Driving from outside

Standard live-command shape; the user-defined endpoints sit next to the built-in ones:

# built-in: snapshot every registered widget
curl -X POST -d '{"name":"imgui_snapshot"}' localhost:9090/command

# user-defined: bump the custom counter by 3
curl -X POST -d '{"name":"bump_counter","args":{"by":3}}' localhost:9090/command

# user-defined: reset
curl -X POST -d '{"name":"reset_counter"}' localhost:9090/command

# framework: trigger a reload (file edit also triggers this)
curl -X POST localhost:9090/reload

The imgui_snapshot payload reflects whatever the most recent bump_counter did — daslang globals and live-command results share one in-memory model.

Next steps

Now that the live-command surface is explicit, next is the driving-from-outside view: the JSON command set the boost layer ships (imgui_force_set / imgui_click / imgui_open / …) treated as its own programming model — a UI that responds to scripted external events the same way it responds to mouse clicks.

See also

Full source: examples/tutorial/live_reload.das

Framework module: live/live_host (the host itself), live/live_commands (the [live_command] annotation), and live/live_vars (the @live serializer).

ImGui-specific lifecycle: imgui/imgui_live.das — the [before_reload] / [after_reload] pair that preserves the ImGui context pointer is the canonical example of a manual hook.

Previous tutorial: Containers

Boost macros — the macro layer.