Reload de Assets
Nesta página
zolo dev também monitora arquivos de dados quando a flag --watch <dir> é
passada (recursiva). Os formatos reconhecidos incluem .json, .toml, .yaml,
.csv, .wgsl, .glsl, .frag, .vert e .hlsl. A cada arquivo alterado,
após um debounce de 150 ms, o runtime chama pub fn __on_asset_reload(path: str, ext: str).
Sem essa definição, o evento é descartado silenciosamente.
Para executar este demo é necessário passar a flag explicitamente:
cd examples/features/21-hot-reload/05-asset-reload
zolo dev main.zolo --watch assets
O módulo app.zolo mantém o config em memória e expõe show() e o hook de asset.
Ao detectar a extensão "json", o hook relê o arquivo com fs::read_to_string e
substitui o config vivo:
Edite assets/config.json (ex.: mude "speed") e observe o hook disparar.
// Feature: HMR of assets — reload config without restarting
// Syntax: global hook `pub fn __on_asset_reload(path: str, ext: str)`
// When to use: games (shaders, sprites), apps with hot config,
// pipelines where data changes more often than the code.
//
// The watcher recognizes: .json .toml .yaml .yml .csv
// .wgsl .glsl .frag .vert .hlsl
// For each such file under `--watch <dir>` (recursive) or the
// implicit directories of the entry/modules, the hook is called.
use std::package
use std::json
let config: any = #{name: "default", speed: 1, color: "gray"}
pub fn show() {
let live = package.loaded["app"]
print("current config: name={live.config.name}, speed={live.config.speed}, color={live.config.color}")
}
pub fn __on_asset_reload(path: str, ext: str) {
let live = package.loaded["app"]
print(">>> asset changed: {path} ({ext})")
if ext == "json" {
let raw = fs::read_to_string(path)
if raw != nil {
live.config = json.parse(raw)
print(">>> config reloaded")
}
}
}
Requer a CLI/host do Zolo — abra no playground ou rode localmente.
O ponto de entrada carrega o JSON inicial e repassa o controle ao loop interativo:
// Feature: hot-reload of data
// Syntax: run with `zolo dev main.zolo --watch assets`.
// When to use: edit config.json and see the app react without restart.
use std::package
use std::json
use app::{show, __on_asset_reload}
fn main() {
// Initial load.
let raw = fs::read_to_string("assets/config.json")
if raw != nil {
let live = package.loaded["app"]
live.config = json.parse(raw)
}
show()
print("ENTER reprints. Edit assets/config.json and save.")
print("Run with: zolo dev main.zolo --watch assets")
while true {
let line = io::read("*l")
if line is nil || line == "q" {
break
}
show()
}
}
Requer a CLI/host do Zolo — abra no playground ou rode localmente.
Desafio
Adicione um campo "theme": "dark" ao assets/config.json e imprima-o em show().
Salve o JSON — o hook deve recarregá-lo sem alterações no código Zolo.