mirror of
https://github.com/Ukendio/jecs.git
synced 2025-04-24 17:10:03 +00:00
2.3 KiB
2.3 KiB
Query API
Queries allow you to efficiently find and iterate over entities that have a specific set of components.
Methods
iter()
function Query:iter(): () -> (Entity, ...)
Returns an iterator that yields matching entities and their component values.
Example: ::: code-group
for id, position, velocity in world:query(Position, Velocity):iter() do
-- Do something with position and velocity
end
for (const [id, position, velocity] of world.query(Position, Velocity)) {
// Do something with position and velocity
}
:::
with()
function Query:with(...: Entity): Query
Adds components to filter by, but doesn't return their values in iteration. Useful for filtering by tags.
Example: ::: code-group
-- Only get position for entities that also have Velocity
for id, position in world:query(Position):with(Velocity) do
-- Do something with position
end
for (const [id, position] of world.query(Position).with(Velocity)) {
// Do something with position
}
:::
without()
function Query:without(...: Entity): Query
Excludes entities that have any of the specified components.
Example: ::: code-group
-- Get position for entities that don't have Velocity
for id, position in world:query(Position):without(Velocity) do
-- Do something with position
end
for (const [id, position] of world.query(Position).without(Velocity)) {
// Do something with position
}
:::
cached()
function Query:cached(): Query
Returns a cached version of the query for better performance when using the same query multiple times.
archetypes()
function Query:archetypes(): { Archetype }
Returns the matching archetypes for low-level query customization.
:::info This method is for advanced users who need fine-grained control over query behavior at the archetype level. :::
Example:
for i, archetype in world:query(Position, Velocity):archetypes() do
local columns = archetype.columns
local field = archetype.records
local P = field[Position]
local V = field[Velocity]
for row, entity in archetype.entities do
local position = columns[P][row]
local velocity = columns[V][row]
-- Do something
end
end