Skip to the content.

Replication

Sends State values from the server to clients. Nothing replicates unless the server explicitly shares it.

-- Server
local replicator = Constella.Replication.Server.new("Game")
replicator:Share("RoundTime", roundTime)              -- every player
replicator:ShareWith(player, "Coins", coinsState)     -- this player only
-- Client
local replica = Constella.Replication.Client.new("Game")
Constella.State.bind(coinsLabel, "Text", replica:Get("Coins"), function(value)
	return if value then `Coins: {value}` else "Coins: ..."
end)

Security

API

Server Description
Replication.Server.new(namespace, { Parent?, Logger?, OnError?, MaxValueBytes?, Delta? }?) Creates its own Network namespace. Delta = true sends table changes as patches (see below)
replicator:Share(name, state) Public. Returns a share with :Stop()
replicator:ShareWith(player, name, state) Private. Removed automatically when the player leaves. For a player who already left (for example after a yielding profile load), returns a share that is already stopped
replicator:Destroy()  
Client Description
Replication.Client.new(namespace, { Timeout? }?) Yields until the initial snapshot arrives
replica:Get(name) A read-only state (nil until the value is known)
replica:Observe(name, fn)  
replica:Destroy()  

A name can be public or private, not both. Private names can be reused across players, so each player can have their own "Coins".

Tables are compared by reference (State semantics). Set a new table to replicate a change; changing a table in place won’t trigger an update.

Delta updates

By default every change sends the whole value. With Delta = true, a change from one table to another is sent as a patch that lists only what changed (recursively), whenever that’s smaller than the whole value:

local replicator = Constella.Replication.Server.new("Game", { Delta = true })
replicator:ShareWith(player, "Inventory", inventory)

local nextValue = table.clone(inventory:Get())
nextValue.Coins += 10
inventory:Set(nextValue) -- about 130 bytes on the wire instead of the whole 40-item inventory (~1.2 KB)