bakpakin / tiny-ecs

ECS for Lua
http://bakpakin.github.io/tiny-ecs/doc/
MIT License
675 stars 61 forks source link

System constructor and deconstructors #6

Closed karai17 closed 9 years ago

karai17 commented 9 years ago

It would be nice if tiny had system constructors that are called immediately when a system is added to or removed from the world. It would also be nice if system.world was added immediately, not after first update.

local system = tiny.system()

function system:onAdd()
end

function system:onRemove()
end

function system:onAddEntity()
end

function system:onRemoveEntity()
end
shakesoda commented 9 years ago

I think it's fine that world gets added on first update - as long as we've got some kind of init/deinit functions which are guaranteed to run before any entities are added and after all have been removed.

There's also no need to break API for this, that's just annoying. We can leave onAdd/onRemove as they are.

The use case we've got is that we have code which needs to be properly constructed and deconstructed or we'll leak memory or not have data loaded, and it'd be nice to be able to do this in a self contained way in the systems instead of manually calling init/deinit functions on the system.

Almost all of our systems have init code which depends on the world in some way, too, so we've had to write all our systems as functions which take the world as an argument (which, again, is a bit annoying)

bakpakin commented 9 years ago

The system.world not being present before the first update is easy to change and really shouldn't break api to change. However, as shakesoda pointed out, i'm not sure its necessary. I like the idea of callbacks for system addition/removal from the world, although with different names so as not to break API. I agree writing systems as functions is very annoying, and the API should not force that upon you.

bakpakin commented 9 years ago

Should the system removal callback be called before or after all entities are removed? I'm thinking probably after.

shakesoda commented 9 years ago

Definitely after.

bakpakin commented 9 years ago

Just pushed an undocumented fix, now there are callbacks onRemoveFromWorld and onAddToWorld in systems. See if these fulfill your needs. Also, now adding a system to a world twice raises an error instead of silently doing nothing.

shakesoda commented 9 years ago

Seems to work great, thanks a bunch!