Skip to content

Persistence

Updated

A Persistable keeps data for its entity on a persistence service, so the data is still there after a reload, the next day, or in a new session: a visit counter, a guest book, a high score, the state of a puzzle. Every peer that holds the same entity reads and writes the same record, so the data is shared as well as kept.

  • You know how to find an entity and get its component in a script. See Working with entities.
  • You can write async functions and use await, try and catch. Every Persistable call goes to the service and returns a promise.
  • You know how a Signal Emitter turns component events into signals. See Scripting.

Persistence and networking solve different problems, and a scene often uses both.

Networkable Persistable
Shares Live state with the people in the room now. Stored data, whoever is connected.
Lasts As long as the room keeps the object. Across reloads and sessions, until it expires or is dropped.
Good for Moving objects, switches, a live scoreboard. Counters, high scores, guest books, saved progress.
  • The Persistable entity (ent-persistable) carries a required Persistable component. Its record is keyed by the entity’s id, which is saved with the scene, so the data comes back after a reload.
  • Values are JSON values stored under string keys, like the fields of an object.
  • Scripts read and write the record through the component. Every call is asynchronous.
  • With a Signal Emitter on the entity, the Persistable reports changes: its own, and those other peers make.
  • Persistable is offered on the Persistable entity and the AI Agent entity.

PersistableComponent, type comp-persistable.

Prop Type Default Description
storage 'memory' or 'disk' 'memory' Which of the service’s two stores keeps the record. A new Persistable entity uses 'disk'.
retention number none How long the record is kept after it was last used, in minutes, from 60 (an hour) to 43 200 (30 days). Each successful read or write renews it. A new Persistable entity uses 10 080 (7 days). Left out, no retention is set.
Member Description
get(key, defaultValue?) The stored value, or defaultValue when the key is absent or the request fails.
set(key, value) Store a value under key, replacing what was there.
delete(key) Remove one key.
inc(key, value) Add value to a stored number.
mult(key, value) Multiply a stored number by value.
arrPush(key, item) Append to a stored array.
arrInsertAt(key, index, item) Insert into a stored array at index.
arrPull(key, value) Remove every occurrence of value from a stored array.
arrPullAt(key, index) Remove the item at index from a stored array.
inspect() The whole stored state, or null on failure.
clear() Reset the stored state to an empty object. Resolves true on success.
drop() Delete the record outright. Resolves true when it was removed or already absent.
ttl(timestamp) Expire the stored state at a Unix timestamp, in milliseconds. Resolves true on success.
lock(timeout) Take the lock for timeout milliseconds, so this instance’s writes are accepted while others are held off. Resolves true when it got it.
unlock() Release a lock this instance holds. Calling it without holding the lock is an error.
locked Whether this instance holds the lock.

The writing calls (set, delete, inc, mult and the arr… calls) resolve to the stored state after the change, and reject when the service refuses. Wrap them in try and catch. delete and arrPull also succeed when there is nothing to remove.

Add a Signal Emitter to the Persistable’s entity to receive these:

Event Data When
Persistable::change { prop?, values?, origin?, eventId? } A write changed the stored state.
Persistable::cleared { values?, origin?, eventId? } The state was emptied with clear() or deleted with drop().
Persistable::error { message } A call failed.
Field Description
prop The key a local write changed, when it named one.
values The stored state after the change.
origin Absent for this peer’s own writes; 'remote' for a change another peer made; 'sync' when the state was read again to catch up.
eventId The id of a remote change, to tell repeats apart.
message What went wrong, on error.
  • Reads (get, inspect) and locking send no event.
  • Changes made by other peers are followed only while the entity has an enabled Signal Emitter with a signal. A Persistable nobody listens to does no background work.
  • Every failure is also written to the script log.
Visits.jx
#pragma lifecycle(startup)
async function startup() {
const store = findEntity('Visits').getComponent(PersistableComponent);
const label = findEntity('Visit Count').getComponent(UILabelComponent);
try {
const state = await store.inc('count', 1);
label.setProps({ text: `Visit number ${state.count}` });
} catch (error) {
const count = await store.get('count', 0);
label.setProps({ text: `Visits: ${count} (offline)` });
}
}
  • inc adds one and resolves to the whole stored state, so state.count is the new total.
  • If the write fails, get with a default still shows something.
GuestBook.jx
#pragma lifecycle(startup)
// Scene: a Persistable entity named "Guest Book" with a Signal Emitter on
// 'guestbook'. A "Name" UI Input with a Signal Emitter on 'guestbook/input',
// and an "Entries" UI Label.
let store;
let entries;
function render(names) {
entries.setProps({ text: (names ?? []).slice(-10).join('\n') || 'Be the first to sign!' });
}
async function startup() {
store = findEntity('Guest Book').getComponent(PersistableComponent);
entries = findEntity('Entries').getComponent(UILabelComponent);
render(await store.get('names', []));
// Our writes and other peers' writes both arrive here.
on('guestbook', (event) => {
if (event.eventType === EventType.Persistable.Change) render(event.data.values?.names);
if (event.eventType === EventType.Persistable.Error) log('Guest book:', event.data.message);
});
on('guestbook/input', async (event) => {
if (event.eventType !== EventType.UIInput.Submit) return;
const name = event.data.text.trim();
if (!name) return;
try {
await store.arrPush('names', name);
} catch (error) {
log('Could not sign the book');
}
});
}
  • arrPush appends to the stored array; the change event carries the full state in values.
  • Because the Signal Emitter has a signal, changes made by other visitors arrive too, with origin: 'remote'.
  • The label shows the last ten names.
HighScore.jx
#pragma lifecycle(startup)
// Scene: a Persistable entity named "Records". Game scripts emit
// 'game/over' with the final score as data.
let store;
async function submit(score) {
// Hold the record while we compare and write, so two players cannot overwrite each other.
if (!(await store.lock(2000))) {
log('Record busy, try again');
return;
}
try {
const best = await store.get('best', 0);
if (score > best) {
await store.set('best', score);
log(`New record: ${score}`);
}
} finally {
if (store.locked) await store.unlock();
}
}
function startup() {
store = findEntity('Records').getComponent(PersistableComponent);
on('game/over', (score) => submit(score));
}
  • lock(2000) holds the record for at most two seconds; while it is held, other peers’ writes are refused.
  • The finally block always releases the lock, checking locked first so unlock is never called without it.
  • emit('game/over', 120) from another script passes 120 straight to the callback.
PuzzleState.jx
#pragma lifecycle(startup)
// Scene: a Persistable entity named "Puzzle" with a Signal Emitter on 'puzzle',
// and a "Reset" UI Button with a Signal Emitter on 'puzzle/reset'.
let store;
async function startup() {
store = findEntity('Puzzle').getComponent(PersistableComponent);
const state = await store.inspect();
log('Saved puzzle:', state ? JSON.stringify(state) : 'unavailable');
on('puzzle', (event) => {
if (event.eventType === EventType.Persistable.Cleared) log('Puzzle was reset');
});
on('puzzle/reset', async (event) => {
if (event.eventType !== EventType.UIButton.Press) return;
if (await store.clear()) {
// Forget it entirely one day from now if nobody plays again.
await store.ttl(Date.now() + 24 * 60 * 60 * 1000);
}
});
}
  • inspect reads the whole record at once, or null when the service cannot be reached.
  • clear empties the state and sends Persistable::cleared to every listening peer.
  • ttl takes an absolute time in milliseconds, so it is built from Date.now().
  • Not awaiting. Every call returns a promise. Without await, you read the promise instead of the value.
  • No try around writes. Writes reject when the service refuses or is unreachable; an uncaught rejection stops the script.
  • Expecting remote changes without a signal. Other peers’ changes are followed only while the entity has a Signal Emitter with a signal.
  • Spawned copies. The record follows the entity’s id. A spawned copy has a new id, so it gets a record of its own.
  • Storing functions or class instances. Only JSON values are stored.