Log inGet started
Package

entity_coerce.module

Newest version

This package holds more than this page lists. See all of its files in its world.

README.md

entity_coerce

Coerce entity-shaped values into one uniform list. Installed by the prelude as entity.ids and entity.refs, so nothing needs to require this module.

An entity travels through the API as one of two values:

  • an id string — "ent_5d305b4377f8d505"
  • an entityRef — the table carrying .position, .component, .name

The engine calls answer with entityRefs — the lookups (find, findAll, spawn, batchProxy) and the hierarchy reads (getChildren, getDescendants, getParent) alike; duplicate answers with an id. Ids also arrive from stored data and serialized scenes. These two functions turn either shape — a lone value, a list, or a mix — into the shape the calling code wants.

Surface

entity.ids(value)     -> { string }   -- id strings
entity.refs(value)    -> { entityRef } -- entityRefs

value is an entity, a list of entities, or nil. Both accept id strings and entityRefs in any combination.

Examples

Iterate a stored list of ids as entityRefs, so the per-entity surface is available without a per-element entity(...) call:

for _, e in entity.refs(savedIds) do
    e.position = { 0, 1, 0 }
end

Take the id form of an entityRef-answering call:

local ids = entity.ids(entity.findAll("Prop"))
entity.batchWrite(ids, "Transform", "translation", values)

Accept "one or many entities" as a single argument, with no branch:

local function paint(targets, material)
    for _, e in entity.refs(targets) do
        e.component.set("Model", { material = material })
    end
end

paint(root, red)                 -- one entityRef
paint(root.id, red)              -- one id
paint(savedIds, red)             -- a list of ids
paint(root.getChildren(), red)   -- a list of entityRefs

Behaviour

  • A single entity coerces to a one-element list.
  • nil coerces to an empty list — the hierarchy reads answer nil for an entity with no children, and an empty loop is the right reading of that.
  • Order is preserved and duplicates are kept.
  • A value that is not an entity raises, naming the element's position. A silently dropped element would come back as a shorter list with no indication of which one went missing.
  • entity.refs raises on an id whose entity has despawned since the collection was read, since it has no entityRef to answer with.

Reading a Field.entityRef field

referencedId(value) answers the id a Field.entityRef field names, for a component that hands the entity on as an id (a native component, an ecs call, a module taking an id string):

local EntityCoerce = require("modules.entity_coerce")
local targetId = EntityCoerce.referencedId(public.target)  -- "" when unset

An entity or an id answers that id. A name answers the id of the entity entity.find finds by it, and the name as written while no entity carries it. nil and "" answer "".