Destroy Physics Object

How do you destroy a physics object. In my game, a random wall is created every time you start a new game. But the problem here is that it doesn’t destroy the older wall. Whhat and where do I put the code to destroy the wall. I’m creating the wall by putting

function createWall()

Same problem with the menu physics, the code is Body.destroy() where Body is the name of your wall. Place it when you end your game or just before you create the wall

this is the code for my wall. I can’t get the ~~~ body.destroy() function ~~~ to work. I have edge chain type

function createWall()
    local points={}
    local x=80
    local y=80
    local margin=80
    
    minx=x
    miny=y
    for x2=x,WIDTH-margin,20 do
        local v=vec2(x2,y)
        y=math.abs(y+math.random(-10,10))
        if (y>miny) then miny=y end
        table.insert(points,v)
        x=x2
    end
    maxx=x
    x=WIDTH - x
    for y2=y+10,HEIGHT -margin-30,20 do
        local v=vec2(WIDTH - x,y2)
        x=math.abs(x+math.random(-10,10))
        if(WIDTH -x<maxx) then maxx=WIDTH -x end
        table.insert(points,v)
        y=y2
    end
    maxy=y
    y=HEIGHT - y
    for x2=WIDTH -x-10,margin,-20 do
        local v=vec2(x2,HEIGHT - y-30)
        y=math.abs(y+math.random(-10,10))
        if (HEIGHT -y<maxy) then maxy=HEIGHT -y end
        table.insert(points,v)
        x=x2
    end
    
    for y2=HEIGHT -y-40,points[1].y,-20 do
        local v=vec2(x,y2)
        if (x>minx) then minx=x end
        x=math.abs(x+math.random(-10,10))
        table.insert(points,v)
    end
    local leftw=physics.body(CHAIN,true,unpack(points))
    table.insert(walls,leftw)
end

what would I call this physics.body and is it possible to destroy it

I would say leftw is your body. You should be able to call destroy on that list item. I would remove it from the list and then call destroy.

I have some question related to this: How does codea handle the memory? Does it keep references on objects and destroy them when the reference counter is zero? E.g. I have classes of objects in a list. I have created them into a local variable before adding them to the list, so no global reference should persist. when I remove them from the list, is it then removed from the memory? I would like to build my code so that it does not waste memory.

Codea uses Lua and Lua uses garbage collection, so basically if an object becomes unreachable (there are no references to it or something that indirectly references it) then it is deleted. Garbage collection is expensive and so its only performed periodically, or when needed (low memory). If you nil a reference to a physics object it will hang around in Codea for a little while due to a delay in garbage collection. Destroy is called automatically when an object is garbage collected, but if you want it to be gone instantly, you need to call destroy manually before clearing references to your object.