Rober Dote
Rober Dote

Reputation: 61

Delete object[i] from table or group in corona sdk

i have a problem (obviusly :P)

i'm create a mini game, and when i touch a Object-A , creates an Object-B. If i touch N times, this create N Object-B.

(Object-B are Bubbles in my game)

so, i try when I touch the bubble (object-B), that disappears or perform any actions. I try adding Object-B to Array

local t = {}

. . .

bur = display.newImage("burbuja.png")
table.insert(t,bur)

and where i have my eventListeners i wrote:

for i=1, #t do
bur[i]:addEventListener("tap",reventar(i))
end

and my function 'reventar'

local function reventar (event,id)
table.remove(t,id)
end

i'm lost, and only i want disappears the bubbles.

Upvotes: 0

Views: 6400

Answers (1)

royi
royi

Reputation: 554

you're probably gonna want to do something like this:

local t = {}

bur = display.newImage("burbuja.png")
table.insert(t,bur)

-- declaring the function first so it can be used later in the for loop
local function reventar(event)
    t[event.target.id] = nil         -- We remove object from table
    event.target:removeSelf()        -- Also remember to remove from display
end

for i=1,#t do
    t[i].id = i
    t[i]:addEventListener("tap", reventar)
end

Hope this helps.

EDIT

I would do it this way, because it's better when you want to loop through the objects:

local t = {}

-- declaring the function first so it can be used later
local function reventar(event)
    event.target.kill = true     -- Mark the clicked object for later destruction
end

bur = display.newImage("burbuja.png")
bur:addEventListener("tap", reventar)
table.insert(t,bur)

local function loop(event)
    for i = #t, 1, -1 do
        local object = t[i]

        -- Do stuff to object here, such as object.y = object.y + 1

        if object.kill then   -- Check if object is marked for destruction
            local child = table.remove(t, i)    -- Remove from table
            if child ~= nil then
                -- Remove from display and nil it
                child:removeSelf()
                child = nil
            end
        end
    end
end

Runtime:addEventListener("enterFrame", loop) -- Remember to remove this when no longer needed

Upvotes: 1

Related Questions