I have a timer which calls a function that creates objects off screen, moves them onto the screen, and then removes them.
Objects are moved with transition.to and then in onComplete I am doing display.remove. Here is a code snippet:
local objects = {} local function createObject(position, spd) print("object count is: " .. #objects) local tmp = display.newImageRect(dsp\_grp, "sprites/object.png", 211, 244) tmp.x, tmp.y = position.startX, position.startY object\_transitions[#object\_transitions + 1] = transition.to(tmp, {time = spd, x = position.endX, onComplete = display.remove}) objects[#objects + 1] = tmp end timer.performWithDelay(frequency, function() createObject(position, speed) end, -1)
My question is: Why is #objects always growing every time I call the print statement? I thought after display.remove the object no longer exists in the table so the table size shouldn’t keep growing?
Firstly, do you even need an objects table, do you do anything with it?
If so, I guess you’ll have to assign each object a unique ID, then to delete iterate through the objects table (backwards) and check the id, as soon as you find the right one, use table.remove and break from the loop.
I thought it was good practice to store everything in case I need to do something in the future. Ex: Pause the game, restart the level, etc…
Maybe I should back up and ask a more fundamental question… When I need to create multiple objects and would like to keep track of them, like enemies, or astroids, etc… Is there a method that’s considered best practice?
Storing them by ID definitely has some advantages here, but I still prefer storing then by number indexes as that is more natural for me at the moment. There was a robust debate about this a year ago and @RoamingGamer made some good points. I have started to switch over to indexing by ID for some of my new modules.
I believe if I were to start from scratch today I might get in the habit of using ID’s as indexes.
I make a ton of #table comparisons to that is my main reason for staying with numbers at the moment.