Builtin Library
README.md
entity_resolve
The id behind an entity reference, whatever shape the reference took.
An entity is written down three ways: as an id string
("ent_5d305b4377f8d505"), as an entity proxy (the table carrying
.position, .component, .name), and — by a person or an agent typing a
call — as the display name the entity carries in its Name component.
entity(ref) answers for the first two. A call that hands it a name gets nil
back, and code that reads that nil as "the entity is gone" either indexes it or
writes somewhere else entirely. This module is the one place that turns any of
the three into the id every engine call takes.
Surface
local resolve = require("modules.entity_resolve")
resolve.id(ref) -> string? -- the id, or nil when nothing matches
resolve.idOrError(ref, slot) -> string -- the id, or a raise naming the miss
ref is an id string, a display name, or an entity proxy. slot names the
argument the reference arrived in, so the raise reads as the call the caller
wrote rather than as a line number inside the callee.
A proxy or an { id = ... } record answers the id written on it. A string is
the shape the scene has to answer for, since a lookup is the only thing that
can say whether it is a name or an id — and both probes stay silent for one
that matches nothing: a name is tested with entity.find, which answers for an
id as well, and then as an id with entity.exists, which raises for a string
naming a live entity and is therefore probed under pcall. A string matching
nothing reaches the caller as nil, with nothing already written to the log on
its behalf.
Examples
Accept whichever shape the caller wrote, then act on the id:
local resolve = require("modules.entity_resolve")
local function raise(target, dy)
local id = resolve.idOrError(target, "target")
local e = entity(id)
e.localPosition = { e.localPosition.x, e.localPosition.y + dy, e.localPosition.z }
end
raise("crate_07", 2) -- a display name
raise("ent_5d305b4377f8d505", 2) -- an id
raise(entity.find("crate_07"), 2) -- a proxy
Answer for a reference that may match nothing, without raising:
local id = resolve.id(maybeGone)
if id ~= nil then
entity(id).despawn()
end