calog/examples/scripts/polyglot/sharedKv.lua

30 lines
1.3 KiB
Lua

-- Shared key/value store across engines: Lua seeds the process-wide kv with a JSON
-- config blob and a numeric counter, then a spawned JavaScript task reads both back
-- (parsing the JSON), prints them, and bumps the counter to 42. Because kv is shared
-- across every engine, Lua sees the JS write: after a short timer it reads the counter
-- again, confirms it is now 42, then tears everything down.
-- Run: bin/calog examples/scripts/polyglot/sharedKv.lua
-- Seed shared state from Lua before spawning the child.
kvSet("config", jsonStringify({ name = "calog", version = 1 }))
kvSet("counter", 41)
calogPrint("lua seeded config and counter =", kvGet("counter"))
-- The child runs on the JavaScript engine and reads/writes the same shared kv.
local jsCode = [[
var config = jsonParse(kvGet("config"));
calogPrint("javascript read config name:", config.name, "version:", config.version);
calogPrint("javascript read counter:", kvGet("counter"));
kvSet("counter", 42);
calogPrint("javascript set counter to 42");
]]
local child = taskSpawn("js", jsCode)
calogPrint("spawned javascript task:", child)
-- Give the JS task time to run its read/write, then observe the shared write from Lua.
timerAfter(300, function()
calogPrint("lua sees counter =", kvGet("counter"))
taskClose(child)
calogExit(0)
end)