calog/examples/scripts/polyglot/pubsubAcrossEngines.lua

29 lines
1.2 KiB
Lua

-- Cross-engine pubsub: Lua subscribes to the "events" topic through the broker,
-- then a spawned JavaScript task publishes a message on that same topic. Because
-- pubsub is process-wide, the Lua handler receives the JS-published message and
-- prints it. The subscribe happens BEFORE the spawn so the child's publish is
-- never missed; a short timer gives delivery time to land, then exits.
-- Run: bin/calog examples/scripts/polyglot/pubsubAcrossEngines.lua
-- Register the Lua handler first so the topic has a listener before anyone publishes.
local subId = psSubscribe("events", function(msg)
calogPrint("lua handler received:", msg)
end)
calogPrint("lua subscribed to 'events' with id:", subId)
-- The child runs on the JavaScript engine and publishes into the shared topic.
local jsCode = [[
var count = psPublish("events", "from JavaScript");
calogPrint("javascript published to", count, "subscriber(s)");
]]
local child = taskSpawn("js", jsCode)
calogPrint("spawned javascript task:", child)
-- Give the JS publish time to be delivered to the Lua handler, then tear down.
timerAfter(300, function()
taskClose(child)
psUnsubscribe(subId)
calogExit(0)
end)