Skip to main content

Query

A query made by [World:query]: the entities that have all of its ids, with their values.

for entity, position, velocity in world:query(Position, Velocity):without(Frozen) do
end
world:query(Position, Velocity):each(function(entity, position, velocity) end)
  • A query never goes stale: its ids may be created and deleted at any time.
  • A query written inline in a system is cheap: queries of the same shape share one state from the second request of the shape, so an inline query allocates only a small handle, and an iteration of a stored query allocates nothing. The first request of a shape gets a light state of its own; kept and used again (a second loop, a modifier, Query:cached), it becomes the shared state. A world shares up to 1024 shapes; the shapes of an entity used as a term are dropped when the entity is deleted.
  • A cached query with scattered matches keeps a list of them; after changes that cost less to re-check than a pass over the bitsets (a quarter of the list, or half of the words of its smallest term) it updates only the changed slots of the list, after more it passes over the bitsets once, and a query that matches nothing costs a check of its ids per loop (a comparison when no id of any cached query changed in the world since its previous loop).
  • The current entity may be changed or deleted inside the loop. Changes of other entities may or may not be seen by the running loop; an entity deleted ahead of the loop is skipped or returned once as a dead id (check World:contains), with the values that its slot holds when the loop reaches it: nil, or those of an entity made during the loop that took the slot, which may also be returned in place of the dead id, even when it does not match.
  • Loops over the same query may be nested. The order is ascending by entity slot.

Functions​

with​

Query:with(...: Id) → Query

Required ids whose values are not returned. Each call replaces the earlier ids of with.

without​

Query:without(...: Id) → Query

Excluded ids. Each call replaces the earlier ids of without.

any​

Query:any(...: Id) → Query

An OR term: the entity has at least one of the ids. Several calls add several terms.

cached​

Query:cached() → Query

Keeps what the query observed and its iteration state between loops. Shared queries (without change filters) are cached already, and the first request of a shape becomes its shared state here; call it on a query with change filters that is stored and iterated many times. A query that has not been iterated yet is prepared now (it picks how it iterates and builds its match list), so that its first loop costs no more than the next ones.

added​

Query:added(
id: Id--

a tracked id (see World:track)

) → Query

Change filter: the entities that got id added since the previous iteration of this query. Each query keeps the first tick it has not seen, up to the last 7 finished ticks (a ring of 8 ticks, the current one included).

changed​

Query:changed(
id: Id--

a tracked id (see World:track)

) → Query

Change filter: the entities whose value of id was set again since the previous iteration of this query.

removed​

Query:removed(
id: Id--

a tracked id (see World:track)

) → Query

Change filter: the entities that lost id since the previous iteration of this query and are still alive.

created​

Query:created() → Query

Change filter: the entities made since the previous iteration of this query and still alive (see World:track_created, which it needs). world:query(Position):created() returns the new entities that have Position now; world:query():created() all of them.

each​

Query:each(callback: (
entity: Entity,
...any
) → ()) → ()

Calls callback(entity, ...values) for every match: the fastest loop.

has​

Query:has(entity: Id) → boolean

Whether the entity matches the query.

spans​

Query:spans() → () → (
number?,
number?,
number
)--

an iterator of first, last, mask

The fast path: runs of matching slots. When mask == 0xFFFFFFFF every slot of first..last matches; otherwise first..last is one 32-slot word and the set bits of mask are the matching slots (first + bit index). Read the values with World:column and the entities with World:alive_table.

count​

Query:count() → number

The number of matches. It does not consume change filters.

add_all​

Query:add_all(id: Id) → ()

Adds id to every entity that matches now. A component or tag without hooks is added 32 entities at a time; pairs and ids with hooks go entity by entity, and every hook runs. A hook that deletes id (or the relation or the target of the pair) ends the operation: the rest of the matches do not get it.

set_all​

Query:set_all(
id: Id<V>,
value: V--

the same value for every match

) → ()

Sets id to value on every entity that matches now (as Query:add_all, also when a hook deletes id).

remove_all​

Query:remove_all(id: Id) → ()

Removes id from every entity that matches now.

delete_all​

Query:delete_all() → ()

Deletes every entity that matches now.

toggle_all​

Query:toggle_all(
id: Id--

a component, a tag or a pair (not a wildcard)

) → ()

Removes id from every entity that matches now and has it, and adds it to every one that does not. A component or tag without hooks is toggled 32 entities at a time; pairs and ids with hooks go entity by entity, and every hook runs. A hook that deletes id (or the relation or the target of the pair) ends the operation.

monitor​

Query:monitor() → Monitor

Calls back when an entity starts or stops matching the query, at the change that makes it happen: an id of the query added or removed, an excluded id removed or added, Disabled, clear, delete, cascades and batch operations. One added per entry and one removed per exit; the entities that match when the monitor is created are members already.

local monitor = world:query(Model):with(Visible):monitor()
monitor.added(function(entity) end)
monitor.removed(function(entity) end) -- before the ids are removed: values can be read
monitor.disconnect()
  • removed runs before the removal, so the values of the entity can still be read; for a delete or clear, before any id goes.
  • added runs after an id is added; when the entity starts matching because an excluded id (or Disabled) is removed, it runs before that removal completes.
  • An exclusive relation (ChildOf) that replaces a pair does not make an entity leave and enter a query that has the relation with any target (ecs.pair(ChildOf, ecs.Wildcard)).
  • A monitor listens to the signals of the ids of the query (see World:added): changes of these ids and deletes of entities that have them run a check, and batch operations on them go entity by entity.
  • The terms may be components, tags, pairs and ecs.pair(R, ecs.Wildcard); a term ecs.pair(ecs.Wildcard, T) and change filters raise an error.
  • The monitor keeps the terms of the query as they are when it is made: with, without or any called on the query afterwards do not change it (the jecs addon copies the query too).
  • A pair keeps the slots of its elements: when the relation of a pair term is deleted and another entity takes its slot, the query matches the pairs of that entity, but the monitor still listens to the deleted one. Make a new monitor after deleting a relation of its terms.
  • A monitor made inside an OnRemove hook or a removed callback takes the entity being changed as it is before the removal (a member that has left already).
  • An entity that a callback deletes while one of its terms is being removed leaves at the latest when its slot is freed (its removed then gets the dead id), before a new entity can take the slot.
  • The callbacks may change the world; an error in one stops the change that ran it, like an error in a hook.
Show raw api
{
    "functions": [
        {
            "name": "with",
            "desc": "Required ids whose values are not returned. Each call replaces the earlier ids of `with`.",
            "params": [
                {
                    "name": "...",
                    "desc": "",
                    "lua_type": "Id"
                }
            ],
            "returns": [
                {
                    "desc": "",
                    "lua_type": "Query"
                }
            ],
            "function_type": "method",
            "source": {
                "line": 1216,
                "path": "src/init.luau"
            }
        },
        {
            "name": "without",
            "desc": "Excluded ids. Each call replaces the earlier ids of `without`.",
            "params": [
                {
                    "name": "...",
                    "desc": "",
                    "lua_type": "Id"
                }
            ],
            "returns": [
                {
                    "desc": "",
                    "lua_type": "Query"
                }
            ],
            "function_type": "method",
            "source": {
                "line": 1224,
                "path": "src/init.luau"
            }
        },
        {
            "name": "any",
            "desc": "An OR term: the entity has at least one of the ids. Several calls add several terms.",
            "params": [
                {
                    "name": "...",
                    "desc": "",
                    "lua_type": "Id"
                }
            ],
            "returns": [
                {
                    "desc": "",
                    "lua_type": "Query"
                }
            ],
            "function_type": "method",
            "source": {
                "line": 1232,
                "path": "src/init.luau"
            }
        },
        {
            "name": "cached",
            "desc": "Keeps what the query observed and its iteration state between loops. Shared queries\n(without change filters) are cached already, and the first request of a shape becomes its\nshared state here; call it on a query with change filters that is stored and iterated many\ntimes. A query that has not been iterated yet is prepared now (it picks how it iterates and\nbuilds its match list), so that its first loop costs no more than the next ones.",
            "params": [],
            "returns": [
                {
                    "desc": "",
                    "lua_type": "Query"
                }
            ],
            "function_type": "method",
            "source": {
                "line": 1243,
                "path": "src/init.luau"
            }
        },
        {
            "name": "added",
            "desc": "Change filter: the entities that got `id` added since the previous iteration of this\nquery. Each query keeps the first tick it has not seen, up to the last 7 finished ticks\n(a ring of 8 ticks, the current one included).",
            "params": [
                {
                    "name": "id",
                    "desc": "a tracked id (see [World:track])",
                    "lua_type": "Id"
                }
            ],
            "returns": [
                {
                    "desc": "",
                    "lua_type": "Query"
                }
            ],
            "function_type": "method",
            "source": {
                "line": 1253,
                "path": "src/init.luau"
            }
        },
        {
            "name": "changed",
            "desc": "Change filter: the entities whose value of `id` was set again since the previous\niteration of this query.",
            "params": [
                {
                    "name": "id",
                    "desc": "a tracked id (see [World:track])",
                    "lua_type": "Id"
                }
            ],
            "returns": [
                {
                    "desc": "",
                    "lua_type": "Query"
                }
            ],
            "function_type": "method",
            "source": {
                "line": 1262,
                "path": "src/init.luau"
            }
        },
        {
            "name": "removed",
            "desc": "Change filter: the entities that lost `id` since the previous iteration of this query\nand are still alive.",
            "params": [
                {
                    "name": "id",
                    "desc": "a tracked id (see [World:track])",
                    "lua_type": "Id"
                }
            ],
            "returns": [
                {
                    "desc": "",
                    "lua_type": "Query"
                }
            ],
            "function_type": "method",
            "source": {
                "line": 1271,
                "path": "src/init.luau"
            }
        },
        {
            "name": "created",
            "desc": "Change filter: the entities made since the previous iteration of this query and still\nalive (see [World:track_created], which it needs). `world:query(Position):created()`\nreturns the new entities that have `Position` now; `world:query():created()` all of them.",
            "params": [],
            "returns": [
                {
                    "desc": "",
                    "lua_type": "Query"
                }
            ],
            "function_type": "method",
            "source": {
                "line": 1280,
                "path": "src/init.luau"
            }
        },
        {
            "name": "each",
            "desc": "Calls `callback(entity, ...values)` for every match: the fastest loop.",
            "params": [
                {
                    "name": "callback",
                    "desc": "",
                    "lua_type": "(entity: Entity, ...any) -> ()"
                }
            ],
            "returns": [],
            "function_type": "method",
            "source": {
                "line": 1287,
                "path": "src/init.luau"
            }
        },
        {
            "name": "has",
            "desc": "Whether the entity matches the query.",
            "params": [
                {
                    "name": "entity",
                    "desc": "",
                    "lua_type": "Id"
                }
            ],
            "returns": [
                {
                    "desc": "",
                    "lua_type": "boolean"
                }
            ],
            "function_type": "method",
            "source": {
                "line": 1295,
                "path": "src/init.luau"
            }
        },
        {
            "name": "spans",
            "desc": "The fast path: runs of matching slots. When `mask == 0xFFFFFFFF` every slot of\n`first..last` matches; otherwise `first..last` is one 32-slot word and the set bits of\n`mask` are the matching slots (`first + bit index`). Read the values with\n[World:column] and the entities with [World:alive_table].",
            "params": [],
            "returns": [
                {
                    "desc": "an iterator of first, last, mask",
                    "lua_type": "() -> (number?, number?, number)"
                }
            ],
            "function_type": "method",
            "source": {
                "line": 1305,
                "path": "src/init.luau"
            }
        },
        {
            "name": "count",
            "desc": "The number of matches. It does not consume change filters.",
            "params": [],
            "returns": [
                {
                    "desc": "",
                    "lua_type": "number"
                }
            ],
            "function_type": "method",
            "source": {
                "line": 1312,
                "path": "src/init.luau"
            }
        },
        {
            "name": "add_all",
            "desc": "Adds `id` to every entity that matches now. A component or tag without hooks is added 32\nentities at a time; pairs and ids with hooks go entity by entity, and every hook runs. A\nhook that deletes `id` (or the relation or the target of the pair) ends the operation: the\nrest of the matches do not get it.",
            "params": [
                {
                    "name": "id",
                    "desc": "",
                    "lua_type": "Id"
                }
            ],
            "returns": [],
            "function_type": "method",
            "source": {
                "line": 1322,
                "path": "src/init.luau"
            }
        },
        {
            "name": "set_all",
            "desc": "Sets `id` to `value` on every entity that matches now (as [Query:add_all], also when a hook\ndeletes `id`).",
            "params": [
                {
                    "name": "id",
                    "desc": "",
                    "lua_type": "Id<V>"
                },
                {
                    "name": "value",
                    "desc": "the same value for every match",
                    "lua_type": "V"
                }
            ],
            "returns": [],
            "function_type": "method",
            "source": {
                "line": 1331,
                "path": "src/init.luau"
            }
        },
        {
            "name": "remove_all",
            "desc": "Removes `id` from every entity that matches now.",
            "params": [
                {
                    "name": "id",
                    "desc": "",
                    "lua_type": "Id"
                }
            ],
            "returns": [],
            "function_type": "method",
            "source": {
                "line": 1338,
                "path": "src/init.luau"
            }
        },
        {
            "name": "delete_all",
            "desc": "Deletes every entity that matches now.",
            "params": [],
            "returns": [],
            "function_type": "method",
            "source": {
                "line": 1344,
                "path": "src/init.luau"
            }
        },
        {
            "name": "toggle_all",
            "desc": "Removes `id` from every entity that matches now and has it, and adds it to every one that\ndoes not. A component or tag without hooks is toggled 32 entities at a time; pairs and ids\nwith hooks go entity by entity, and every hook runs. A hook that deletes `id` (or the\nrelation or the target of the pair) ends the operation.",
            "params": [
                {
                    "name": "id",
                    "desc": "a component, a tag or a pair (not a wildcard)",
                    "lua_type": "Id"
                }
            ],
            "returns": [],
            "function_type": "method",
            "source": {
                "line": 1354,
                "path": "src/init.luau"
            }
        },
        {
            "name": "monitor",
            "desc": "Calls back when an entity starts or stops matching the query, at the change that makes it\nhappen: an id of the query added or removed, an excluded id removed or added, `Disabled`,\n`clear`, `delete`, cascades and batch operations. One `added` per entry and one `removed`\nper exit; the entities that match when the monitor is created are members already.\n\n```lua\nlocal monitor = world:query(Model):with(Visible):monitor()\nmonitor.added(function(entity) end)\nmonitor.removed(function(entity) end) -- before the ids are removed: values can be read\nmonitor.disconnect()\n```\n\n- `removed` runs before the removal, so the values of the entity can still be read; for a\n  `delete` or `clear`, before any id goes.\n- `added` runs after an id is added; when the entity starts matching because an excluded id\n  (or `Disabled`) is removed, it runs before that removal completes.\n- An exclusive relation (`ChildOf`) that replaces a pair does not make an entity leave and\n  enter a query that has the relation with any target (`ecs.pair(ChildOf, ecs.Wildcard)`).\n- A monitor listens to the signals of the ids of the query (see [World:added]): changes of\n  these ids and deletes of entities that have them run a check, and batch operations on\n  them go entity by entity.\n- The terms may be components, tags, pairs and `ecs.pair(R, ecs.Wildcard)`; a term\n  `ecs.pair(ecs.Wildcard, T)` and change filters raise an error.\n- The monitor keeps the terms of the query as they are when it is made: `with`, `without`\n  or `any` called on the query afterwards do not change it (the jecs addon copies the query\n  too).\n- A pair keeps the slots of its elements: when the relation of a pair term is deleted and\n  another entity takes its slot, the query matches the pairs of that entity, but the\n  monitor still listens to the deleted one. Make a new monitor after deleting a relation\n  of its terms.\n- A monitor made inside an `OnRemove` hook or a `removed` callback takes the entity being\n  changed as it is before the removal (a member that has left already).\n- An entity that a callback deletes while one of its terms is being removed leaves at the\n  latest when its slot is freed (its `removed` then gets the dead id), before a new entity\n  can take the slot.\n- The callbacks may change the world; an error in one stops the change that ran it, like\n  an error in a hook.",
            "params": [],
            "returns": [
                {
                    "desc": "",
                    "lua_type": "Monitor"
                }
            ],
            "function_type": "method",
            "source": {
                "line": 1397,
                "path": "src/init.luau"
            }
        }
    ],
    "properties": [],
    "types": [],
    "name": "Query",
    "desc": "A query made by [World:query]: the entities that have all of its ids, with their values.\n\n```lua\nfor entity, position, velocity in world:query(Position, Velocity):without(Frozen) do\nend\nworld:query(Position, Velocity):each(function(entity, position, velocity) end)\n```\n\n- A query never goes stale: its ids may be created and deleted at any time.\n- A query written inline in a system is cheap: queries of the same shape share one\n  state from the second request of the shape, so an inline query allocates only a small\n  handle, and an iteration of a stored query allocates nothing. The first request of a\n  shape gets a light state of its own; kept and used again (a second loop, a modifier,\n  [Query:cached]), it becomes the shared state. A world shares up to 1024 shapes; the shapes\n  of an entity used as a term are dropped when the entity is deleted.\n- A cached query with scattered matches keeps a list of them; after changes that cost less\n  to re-check than a pass over the bitsets (a quarter of the list, or half of the words of\n  its smallest term) it updates only the changed slots of the list, after more it passes\n  over the bitsets once, and a query that matches nothing costs a check of its ids per loop\n  (a comparison when no id of any cached query changed in the world since its previous\n  loop).\n- The current entity may be changed or deleted inside the loop. Changes of other\n  entities may or may not be seen by the running loop; an entity deleted ahead of the\n  loop is skipped or returned once as a dead id (check [World:contains]), with the values\n  that its slot holds when the loop reaches it: nil, or those of an entity made during the\n  loop that took the slot, which may also be returned in place of the dead id, even when it\n  does not match.\n- Loops over the same query may be nested. The order is ascending by entity slot.",
    "source": {
        "line": 1208,
        "path": "src/init.luau"
    }
}