2
votes

Been trying to work this out for hours and not getting anywhere despite lots of searching, so if somebody can help that would be great

My issue is I have a table of objects which are added like this

enemies[enemy_id] = enemy

Now when there is a collision at the end of the map I want to remove that enemy from the table. I have tried removing by

enemies[enemy_id] = nil

But when it gets to the last enemy the table is already empty for some reason. Say there's 3 enemies in a table, I print the count of the table. The first one is removed it shows 2 left, 2nd is removed it shows 0 left. Doesn't make sense

So how do you remove an item from a table? I have also tried table.remove but I need to key the same keys because they are the id of the enemy. I can post an example if need be

2
Don't use #t on sparse tables (when indices have gaps), it returns wrong result. - Egor Skriptunoff
@Luke not sure what you mean by "... I need to key the same keys". - greatwolf

2 Answers

2
votes

When working with "sparse keys" in Lua tables this pattern usually pays off for me:

-- add item to registry
registry[object] = key
registry[key] = object

-- iterate over all items in registry
for k,v in pairs(registry) do 
  if type(k) == "number" then do_something(k,v) end
end

-- remove item with key K from registry:
registry[registry[K]] = nil
registry[K] = nil

-- remove item O from registry:
registry[registry[O]] = nil
registry[O] = nil
1
votes

Since # won't work on sparse arrays, as other suggested, and my solution would be to use 0 index (or simply another variable) as count:

enemies[0] = 0

Then, when you add an enemy, increase the counter, when you remove one, decrease it. Simple as that.