Adds symmetic and idempotent function add (#26)

* Adds symmetic function add

* Should be componentId not entityId
This commit is contained in:
Marcus 2024-05-07 21:32:56 +02:00 committed by GitHub
parent 887c892c2e
commit bf5908a8f5
No known key found for this signature in database
GPG key ID: B5690EEEBB952194

View file

@ -274,15 +274,6 @@ end
local function archetypeTraverseAdd(world: World, componentId: i53, from: Archetype): Archetype local function archetypeTraverseAdd(world: World, componentId: i53, from: Archetype): Archetype
from = from or world.ROOT_ARCHETYPE from = from or world.ROOT_ARCHETYPE
if not from then
-- If there was no source archetype then it should return the ROOT_ARCHETYPE
local ROOT_ARCHETYPE = world.ROOT_ARCHETYPE
if not ROOT_ARCHETYPE then
ROOT_ARCHETYPE = archetypeOf(world, {}, nil)
world.ROOT_ARCHETYPE = ROOT_ARCHETYPE :: never
end
from = ROOT_ARCHETYPE
end
local edge = ensureEdge(from, componentId) local edge = ensureEdge(from, componentId)
local add = edge.add local add = edge.add
@ -307,6 +298,22 @@ local function ensureRecord(entityIndex, entityId: i53): Record
return record :: Record return record :: Record
end end
function World.add(world: World, entityId: i53, componentId: i53)
local record = ensureRecord(world.entityIndex, entityId)
local from = record.archetype
local to = archetypeTraverseAdd(world, componentId, from)
if from then
moveEntity(world.entityIndex, entityId, record, to)
else
if #to.types > 0 then
newEntity(entityId, record, to)
onNotifyAdd(world, to, from, record.row, { componentId })
end
end
end
-- Symmetric like `World.add` but idempotent
function World.set(world: World, entityId: i53, componentId: i53, data: unknown) function World.set(world: World, entityId: i53, componentId: i53, data: unknown)
local record = ensureRecord(world.entityIndex, entityId) local record = ensureRecord(world.entityIndex, entityId)
local from = record.archetype local from = record.archetype