Saltar al contenido

Preservación de Estado

En esta página

Cuando la VM hace el swap de un módulo, fusiona las nuevas exportaciones sobre la tabla existente. Para valores no-función, si el tipo de runtime de la copia viva coincide con el del nuevo inicializador, la copia viva se conserva y el nuevo literal se descarta. Así es como un contador sigue creciendo incluso después de editar la función que lo imprime.

El módulo counter mantiene el estado interno en state, un mapa con el campo count. Para incrementar correctamente el valor que sobrevive entre swaps, la escritura debe hacerse a través de package.loaded["counter"] — nunca mediante una captura local, que apunta a la copia antigua tras el swap.

Edita solo el formato del print; el número sigue creciendo sin reiniciarse.

counter.zolo
Playground
// Feature: state preserved by type on hot-reload

// Syntax: `pub let counter = 0` — literal initializer.

// When to use: we want to edit the fn but keep the accumulated value.

//

// Critical pattern: to mutate the preserved value, write via

// `package.loaded["counter"]`. Mutations through a `local` captured

// inside the closure only affect the old version of the module after swap.


use std::package

let state = #{count: 0}

pub fn bump() {
  let live = package.loaded["counter"]
  // Edit the string below while the program runs — the number

  // keeps growing, it does NOT reset to 0.

  live.state.count = live.state.count + 1
  print("Count: {live.state.count}")
}

Requiere la CLI o el host de Zolo; ábrelo en el playground o ejecútalo localmente.

El punto de entrada simplemente llama a bump() en cada ENTER, sin ningún conocimiento del mecanismo de preservación:

main.zolo
Playground
// Feature: state lives across reloads

// Syntax: `pub let` with a stable runtime type is preserved.

// When to use: counters, caches, sessions — anything you want

// to keep "alive" across edits.


use counter::{bump}

fn main() {
  print("ENTER increments the counter. 'q' to quit.")
  print("Edit counter.zolo (e.g. the print format) — the value persists.")
  while true {
    let line = io::read("*l")
    if line is nil || line == "q" {
      break
    }
    bump()
  }
}

Requiere la CLI o el host de Zolo; ábrelo en el playground o ejecútalo localmente.

Desafío

Agrega un segundo campo max_seen: int = 0 al mapa state en counter.zolo y actualiza bump() para registrarlo. Edita y guarda varias veces: confirma que max_seen se preserva entre reloads igual que count.

Buscar en Zolo

9 resultados

enespt-br