Skip to the content.

State

local State = require(Packages.Constella.State)

local health = State.new(100)
local maxHealth = State.new(100)
local percent = State.computed({ health, maxHealth }, function(h, m) return h / m end)

percent:Observe(function(value) bar.Size = UDim2.fromScale(value, 1) end)
health:Set(50)

Guarantees

Rules

API

Member Description
State.new(value, { Equals? }?) Writable Value<T>
State.computed(sources, fn, { Equals? }?) Read-only Computed<T>. fn receives the source values in order
State.select(source, fn, options?) Shorthand for a single-source computed state
State.batch(fn) Delivers notifications once fn returns. Re-raises errors from fn after delivery
state:Get()  
state:Set(value) / state:Update(fn) Writable states only
state:Subscribe(fn) fn(new, old). Returns a Connection (works with Cleanup:Add)
state:Observe(fn) Calls fn(current) right away, then on every change
state:Destroy() / state:IsDestroyed()  
State.is(value) Type check

UI bindings

local binding = State.bind(coinsLabel, "Text", coins, function(value)
	return `Coins: {value}`
end)
State.bind(healthBar, "Size", healthFraction, function(f) return UDim2.fromScale(f, 1) end)

State.bind(instance, property, state, transform?) sets the property straight away and again on every change. It works with writable and computed states.

To get server values onto the client, see Replication.

Not included

Automatic dependency tracking. Computed states use explicit source lists.