Do Not Use Numeric Indexes
I say this all the time, but nobody listens to me.
Do not use numerically indexed tables to track game objects.
enemyarray[1] = enemy1
Use the objects as the index instead:
enemyarray[enemy1] = enemy1
It is simpler, and not going to make any impact on iteration-speed for reasonable numbers of objects.
Best Known Method
This is the BEST way I know of to create objects that are in a list and have them manage their own reference in the list.
local enemies = {} -- the list of enemies -- A common/shared finalize method to remove an enemy object from the enemies list. local function enemyFinalize( self ) enemies[self] = nil end -- A enemy builder function local makeEnemy( group, x, y ) -- make it local obj = display.new.... group:insert( enemy ) -- put it in the 'list' enemies[obj] = obj -- add and set up finalize listener obj.finalize = enemyFinalize obj:addEventListener("finalize") -- return reference in case you need it return obj end
Now, you can make enemies with your builder:
makeEnemy( 100, 100 )
How Do I Iterate Over The Table?
for \_, enemy in pairs( enemies ) do -- do whatever you need to with enemies here print( enemy.x, enemy.y) end
How Do I Clean Up When Deleting Enemies?
You don’t need to. Just delete the enemy.
For example, this look will delete all enemies in the table and they will all clean up their own entry:
for \_, enemy in pairs( enemies ) do display.remove( enemy ) -- Tip: never use obj:removeSelf() end
How Do I Count Entries In The Table?
Maybe you need to count entries are are confused about how.
Just add this code in main.lua (or elsewhere before you need to call it)
-- == -- table.count( src ) - Counts all entries in table (non-recursive) -- == function table.count( src ) local count = 0 if( not src ) then return count end for k,v in pairs(src) do count = count + 1 end return count end
Now, you can count the enemies table like this:
print("Num enemies == ", table.count( enemies ) )