Skip to main content
Version: Next

Lua Scripting

Several features in the platform evaluate Lua scripts at runtime. Scripts are used to compute entity keys, display labels and virtual property values, and to implement actions and lifecycle hooks. All scripts receive the current entity instance via the self variable.

Scripting Contexts​

FeatureFieldLocationself isMay change entities
Key computationkey_scriptOn EntityType or RelationshipTypeThe entity instanceno
Label computationlabel_scriptOn EntityType or RelationshipTypeThe entity instanceno
Virtual propertyscriptOn has_virtual_prop edgeThe entity instanceno
ActionscriptOn executable_scriptThe entity the action is called onyes
Lifecycle hook (pre)scriptOn the has_hook targetThe entity being writtenyes -- changes to self are folded into the write (see Writing From a Hook)
Lifecycle hook (post)scriptOn the has_hook targetThe entity just writtenno

Hook scripts additionally receive an event table -- see Actions & Hooks.

The self Variable​

Inside every script, self refers to the current entity instance. The available fields mirror the entity's wire format:

AccessReturns
self.properties["<name>"]The value of a property
self.properties["<name>"][LangCode.en_US]A specific locale from a multi-language property
self.relationships["<name>"]The relationship instances of that name; each exposes .target
self.idThe id of the commit the script started on
self.root_idThe entity's root_id (stable identity)
self.source / self.targetOnly on a relationship instance: the source's root_id and the target entity

Reading Other Entities​

FunctionPurpose
ents.load("type/key")Loads any entity by address
get_entity(uuid)Loads any entity by id
rel.targetThe target entity of a relationship instance

A script can walk the graph through relationships:

local total = 0
for _, rel in ipairs(self.relationships["has_ingredient"]) do
total = total + rel.target.properties["weight"]
end
return total

Reads go straight to the engine, so they see the state of the write in progress, not an outdated snapshot.

Changing Entities​

Scripts that may change entities (actions and pre hooks) do so by assigning property values. There is nothing to call: the engine collects everything the run assigned and writes it automatically when the run ends.

self.properties["status_note"] = "checked"
self.properties["title"][LangCode.en_US] = "Checked"
return "ok"

Creating Entities: ents.create​

ents.create("type", {...}) creates a new entity; ents.load reaches an existing one:

local p = ents.load("vegetable/potato")
p.properties["weight"] = 5

local v = ents.create("vegetable", { key = "carrot", properties = { weight = 2 } })
v.properties["colour"] = "orange"

Neither writes anything immediately -- a created entity exists once the run ends. Until then it is visible to its own run only: ents.load finds what the script just created. v.id is valid from the first line.

Rules for Writing​

All of these rules are enforced:

  • One commit per aggregate, written at the end. The script only assigns; the engine writes when the run ends. A loop assigning one property a thousand times still produces one commit.
  • A script run is atomic. Everything it assigned is written together, in one batch. If the script raises an error, nothing is written -- however far it got.
  • The unit of a write is the aggregate. Assignments to self and to anything it owns -- an edge, a list item, a component, a trait instance -- become one new commit of the aggregate. Entities in different aggregates each get their own commit, in the same batch.
  • The write goes through the normal save path. It is subject to the same checks as an API update: read-only or released lifecycle status, branch writability, required and unique values. It fires the entity's hooks and change notifications.
  • A script cannot see the commit it will become. self.id is the commit the run started on. What a script can see are its own assigned values: a property read after an assignment returns the new value, also through a different handle on the same entity.
  • Property values only. Any declared property type can be assigned. The structure of relationships, traits and lists is read-only for scripts, as are key and label.
  • Nothing fails silently. An unknown property name, a virtual property, a value of the wrong type or an unsupported Lua value raises an error at the assignment and fails the run. There is no pcall in the sandbox, so a script cannot swallow such an error.
  • At most 32 aggregates per run. Assigning to the same aggregate repeatedly counts once. Created entities count too.

Scripts in positions that may not write (key_script, label_script, virtual properties) raise an error on assignment. Key and label scripts run before the entity is validated, and virtual properties are recomputed by every save in an order only the engine decides, so a side effect there would run an unpredictable number of times.

note

There is no commit() function: changes are written automatically when the run ends. Calling self:commit() fails the run, and nothing is written.

Writing From a Hook​

A pre hook may change self, and the change is folded into the commit that is about to be saved -- no second commit, nothing to call:

-- pre hook on on_create
self.properties["slug"] = string.lower(self.properties["name"][LangCode.en_US])
return true

The folded values are validated exactly like the caller's own payload: required values, uniqueness and the key are checked again before anything is saved. A value the caller could not have sent cannot be introduced by the hook either.

Only self is folded. Other entities the hook changes (via ents.load(...) or get_entity(...)) are written as separate commits in the same batch.

A post hook cannot change its own entity -- that commit is already written. In v1, post hooks cannot change other entities either.

Examples​

Key Script: Use a Property as the Key​

Define a key_script on the entity type so that instances are keyed by a business identifier rather than a UUID:

return self.properties["material_number"]

With this script, a part entity with material_number = "MAT-001" would be addressable as part/MAT-001.

warning

Properties used in a key_script should be marked as unique on the has_prop edge to avoid key collisions. The engine enforces key uniqueness at write time and will reject the operation if a duplicate key is detected.

Key Script: Composite Key​

Combine multiple properties into a single key:

return self.properties["country"] .. "_" .. self.properties["city"]

Label Script: Localized Display Name​

Use a multi-language property as the display label:

return self.properties["name"][LangCode.en_US]

If the entity has name: { "en_us": "Potato", "de_de": "Kartoffel" }, the @label field will be "Potato".

Label Script: Formatted Label​

Combine multiple properties into a formatted label:

return self.properties["name"][LangCode.en_US] .. " (" .. tostring(self.properties["weight"]) .. " kg)"

Result: "Potato (5 kg)".

Virtual Property: Derived Calculation​

Compute a value from other properties; it is stored when the entity is saved:

return tostring(self.properties["weight"] * 2)

See Virtual Properties for how to declare virtual properties on an entity type.

Action Script: Inline Logic​

A simple action that returns a string:

return "Action executed for " .. self.properties["name"][LangCode.en_US]

An action that changes the entity -- the change is saved as a new commit when the script ends:

self.properties["checked"] = true
return "checked"

See Actions & Hooks for how to declare and invoke actions.

Best Practices​

  • Keep scripts simple. Complex business logic should live in external services (via service_function), not in inline Lua scripts.
  • Always return a value. Key scripts and label scripts must return a string. Virtual property scripts must return a value matching the declared output type.
  • Handle missing values. If a property might be nil, guard against it to avoid runtime errors:
local name = self.properties["name"]
if name then
return name[LangCode.en_US] or "unnamed"
end
return "unnamed"