remove object in a table using a for cycle inside a runtime function

Hi guys, in my game I need to remove all the objects contained inside a specific table using a for cycle inside a runtime function.

The code I’m actually using (which doesn’t work) is the following:

local function cambioScenario() if(immaginiCambioScenario[1].x\<0)then for i=0, 16 do newYork[i]:removeSelf() newYork[i] = nil end end end Runtime:addEventListener("enterFrame", cambioScenario)

The code above returns the following error: 

game.lua:10366: attempt to index field '?' (a userdata value)

Where line 10366 is “newYork[i]:removeSelf()”

By the way, if the for cycle is executed when a Touch Event occurs everything works.

Have you got any suggestions?

Thanks in advantage :slight_smile:

The above means that you have an object that is newYork[0], which isn’t a normal spawned object. In addition, another problem that is going to arise is that this removal function is going to be called every frame that the immaginiCambioScenario object’s X coordinate is below 0. Again, perhaps you have another call to keep this situation from being called every frame in the Runtime listener, but since it isn’t in the above snippet, I’m going to have to go off of what I see.

You might want to add a print statement in there to see what is actually being actioned in that function call and what you can do to mitigate the above (perceived) issues.

An extra tip: Lua array indexing traditionally starts at 1, not 0. You can of course start at any number you like, 0 or 1 or -172, but when using external libraries you may face issues if you don’t follow the convention. I don’t know how you created “newYork”, but if you create an array e.g. like this:

a = {1, 2, 3, 4, 5}

then the first element is a[1], not a[0]

The above means that you have an object that is newYork[0], which isn’t a normal spawned object. In addition, another problem that is going to arise is that this removal function is going to be called every frame that the immaginiCambioScenario object’s X coordinate is below 0. Again, perhaps you have another call to keep this situation from being called every frame in the Runtime listener, but since it isn’t in the above snippet, I’m going to have to go off of what I see.

You might want to add a print statement in there to see what is actually being actioned in that function call and what you can do to mitigate the above (perceived) issues.

An extra tip: Lua array indexing traditionally starts at 1, not 0. You can of course start at any number you like, 0 or 1 or -172, but when using external libraries you may face issues if you don’t follow the convention. I don’t know how you created “newYork”, but if you create an array e.g. like this:

a = {1, 2, 3, 4, 5}

then the first element is a[1], not a[0]