From b870b5a34e35de91a313ad57e6212b1e26ecde44 Mon Sep 17 00:00:00 2001 From: bakpakin Date: Tue, 8 Sep 2015 13:36:27 -0400 Subject: [PATCH] Add onAddToWorld and onRemoveFromWorld callbacks to systems. Also, adding or removing systems to a world twice raises an error. --- spec/tiny_spec.lua | 9 +++++++-- tiny.lua | 30 ++++++++++++++++++------------ 2 files changed, 25 insertions(+), 14 deletions(-) diff --git a/spec/tiny_spec.lua b/spec/tiny_spec.lua index 83e62c1..b2ba9a6 100644 --- a/spec/tiny_spec.lua +++ b/spec/tiny_spec.lua @@ -120,6 +120,11 @@ describe('tiny-ecs:', function() timePassed = 0 end) + after_each(function() + world:clearSystems() + world:refresh() + end) + it("Create World", function() assert.equals(world:getEntityCount(), 3) assert.equals(world:getSystemCount(), 2) @@ -196,7 +201,7 @@ describe('tiny-ecs:', function() it("Add Systems Multiple Times", function() world:update(1) - world:add(moveSystem, oneTimeSystem) + assert.has_error(function() world:add(moveSystem, oneTimeSystem) end, "System already belongs to a World.") world:update(2) assert.equals(2, world:getSystemCount()) assert.equals(3, world:getEntityCount()) @@ -206,7 +211,7 @@ describe('tiny-ecs:', function() world:update(1) world:remove(moveSystem) world:update(2) - world:remove(moveSystem) + assert.has_error(function() world:remove(moveSystem) end, "System does not belong to this World.") world:update(2) assert.equals(1, world:getSystemCount()) assert.equals(3, world:getEntityCount()) diff --git a/tiny.lua b/tiny.lua index 972d7a0..fae5dbe 100644 --- a/tiny.lua +++ b/tiny.lua @@ -449,7 +449,7 @@ function tiny.remove(world, ...) if isSystem(obj) then tiny_removeSystem(world, obj) else -- Assume obj is an Entity - tiny_removeEntity(world, obj) + tiny_removeEntity(world, obj) end end end @@ -476,19 +476,21 @@ function tiny_manageSystems(world) for i = 1, #s2r do local system = s2r[i] local index = system.index - if system.world == world then - local onRemove = system.onRemove - if onRemove then - local entityList = system.entities - for j = 1, #entityList do - onRemove(system, entityList[j]) - end - end - tremove(systems, index) - for j = index, #systems do - systems[j].index = j + local onRemove = system.onRemove + if onRemove then + local entityList = system.entities + for j = 1, #entityList do + onRemove(system, entityList[j]) end end + tremove(systems, index) + for j = index, #systems do + systems[j].index = j + end + local onRemoveFromWorld = system.onRemoveFromWorld + if onRemoveFromWorld then + onRemoveFromWorld(system, world) + end s2r[i] = nil -- Clean up System @@ -514,6 +516,10 @@ function tiny_manageSystems(world) local index = #systems + 1 system.index = index systems[index] = system + local onAddToWorld = system.onAddToWorld + if onAddToWorld then + onAddToWorld(system, world) + end -- Try to add Entities local onAdd = system.onAdd