Moonkis wrote:Please add a suggestion of how to do it, I'm still a newbie to Lua and I'm interessted in alternative solutions!
I'm assuming you're talking about backward iteration for your entities. If so, here's how you would do it:
Code: Select all
for a = #EntityManager.objects, 1, -1 do
local Entity = EntityManager.objects[a]
if Entity.update then
Entity:update(dt)
end
if not Entity:isAlive() then
table.remove( EntityManager.objects, a )
end
end
If you don't understand what's going on here, don't hesitate to ask!
Moonkis wrote:* How to correctly add item to table WHILE iterating over it?
It depends on the situation. If you want the newly added item to be updated immediately, that would be fairly complex. If you were alright with it being updated later, though, it would be easier.
Here's how you would do the easier one:
Code: Select all
for a = #EntityManager.objects, 1, -1 do
local Entity = EntityManager.objects[a]
if Entity.update then
Entity:update(dt)
end
if not Entity:isAlive() then
table.remove( EntityManager.objects, a )
end
if ThingHappensHereThatMakesNewEntity then
table.insert( EntityManager.objects, Thing ) -- Thing being what you want inserted.
end
end
The first option is much more difficult. I'll give it a whirl (warning: code is untested).
Code: Select all
for a = #EntityManager.objects, 1, -1 do
local Entity = EntityManager.objects[a]
if Entity.update then
Entity:update(dt)
end
if not Entity:isAlive() then
table.remove( EntityManager.objects, a )
end
if ThingHappensHereThatMakesNewEntity then
ShiftTable( a, EntityManager.objects )
Table[a - 1] = Thing -- Thing still being the added item.
end
local function ShiftTable( Start, Table )
for e = 1, #Table do
Table[e + 1] = e
end
end
end
That should work, but don't hold me to it. I probably made a mistake somewhere.
Mookis wrote:* I know I can delete items from tables when iterating backwards, but rumors say you can "nil" an index also, how do you do that correctly?
Code: Select all
if not Entity:isAlive() then
EntityManager.objects[a] = nil
end
Hope this helps!