Skip to main content

Channels

Contains functions for sending and receiving data over channels.

Functions​

subscribe(channelName, callback)​

Starts listening on the specified channel and sets a callback function that will be called whenever data is received on the channel.

Parameters​

  • channelName — A string containing the name of the channel.
  • callback — Function to be called whenever data is received on the channel.

Example​

Make an NPC start patrolling after 3 seconds. Note: for this example to work you have to have another Entity publishing on 'channels-patrol' channel.

-- This code is on the patrolling npc
local isPatrolling = false
local function patrol(value)
if isPatrolling == value then return end
isPatrolling = value
while isPatrolling do
Movement.move(Bearing.South)
Movement.move(Bearing.East)
Movement.move(Bearing.North)
Movement.move(Bearing.West)
end
end

function onStart()
Channels.subscribe('channels-patrol',patrol)
end

unsubscribe(channelName, callback)​

Stops listening on the specified channel and removes the callback function.

Parameters​

  • channelName — A string containing the name of the channel.
  • callback — Function to remove from receiving data.

Example​

Make an NPC start moving every 3 seconds. Then stop moving after doing it twice. Note: for this example to work you have to have another Entity publishing 'channels-move' every 3 seconds.

local moveCounter = 0

local function moveNorthAndSouth()
Movement.move(Bearing.North)
Movement.move(Bearing.South)
moveCounter = moveCounter + 1
if moveCounter > 1 then
Channels.unsubscribe('channels-move', moveNorthAndSouth)
end
end

function onStart()
Movement.setSpeed(4)
Channels.subscribe('channels-move',moveNorthAndSouth)
end

publish(channelName, data)​

Sends data to the specified channel.

Parameters​

  • channelName — A string containing the name of the channel.
  • data — Data to send to the channel. All functions subscribed to the channel will be called.

Example​

Make a NPC start patrolling. Note: for this example to work another Entity needs to be subscribed to 'robot-patrol' channel.

-- This code is on the interactable npc

function onStart()
Channels.publish('robot-patrol', true)
end

isSubscribed(channelName)​

Returns true if the specified channel has any subscribers.

Parameters​

  • channelName — String name of the channel.