Use this file to discover all available pages before exploring further.
Relationships make it possible to describe entity graphs natively in ECS. They enable you to model hierarchies, inventory systems, social connections, and any other graph-based data structures.
Use jecs.pair() to create a relationship pair, then add it to an entity:
local jecs = require("@jecs")local pair = jecs.pairlocal world = jecs.world()local Eats = world:component()local Likes = world:component()local Apples = world:entity()local alice = world:entity()local bob = world:entity()-- Add relationshipsworld:add(bob, pair(Eats, Apples))world:add(bob, pair(Likes, alice))world:add(alice, pair(Likes, bob))-- Test if entity has a relationshipprint(world:has(bob, pair(Eats, Apples))) -- true
Find all entities that have a specific relationship with a specific target:
-- Find all entities that eat applesfor entity in world:query(pair(Eats, Apples)) do print(`Entity {entity} eats apples`)end-- Find all entities that like alicefor entity in world:query(pair(Likes, alice)) do print(`Entity {entity} likes alice`)end
The built-in jecs.ChildOf relationship is the standard way to create hierarchies:
local ChildOf = jecs.ChildOflocal parent = world:entity()local child1 = world:entity()local child2 = world:entity()world:add(child1, pair(ChildOf, parent))world:add(child2, pair(ChildOf, parent))-- Find all children of a parentfor child in world:query(pair(ChildOf, parent)) do print(`Entity {child} is a child of parent {parent}`)end
When a parent is deleted, all children with ChildOf are automatically deleted too. See Cleanup Traits for details.
Relationship queries can be combined with regular component queries:
local Position = world:component()local Health = world:component()local player = world:entity()world:set(player, Position, Vector3.new(10, 20, 30))world:set(player, Health, 100)world:add(player, pair(ChildOf, parent))-- Find all children that have Position and Healthfor entity, pos, health in world:query(Position, Health, pair(ChildOf, parent)) do print(`Child {entity} has position {pos} and health {health}`)end
Just like components, relationship pairs can store data:
local Eats = world:component() :: jecs.Id<{ amount: number }>local Apples = world:entity()local entity = world:entity()-- Set relationship with dataworld:set(entity, pair(Eats, Apples), { amount = 5 })-- Query and access the datafor e, eats_data in world:query(pair(Eats, Apples)) do print(`Entity {e} eats {eats_data.amount} apples`)end