1
votes

I am trying to randomly spawn objects which move toward a ball that can be dragged around the screen. Basically I just want the user to try to avoid these objects. I am trying to make the arrows spawn and move toward the balls location and then despawn after a time. This code here works fine for the first arrow but when it tries to delete the second one it calls and error saying attempt to call method 'remove self' (a nil value).

local function cleararray()
    if ( object[objectTag] ) then
        object[objectTag]:removeSelf()
    end
end

local function spawnObject()
    objectTag = objectTag + 1
    local objIdx = mRandom(#objects)
    local objName = objects[objIdx]
    object[objectTag]  = display.newImage("btn_arrow.png") 
    object[objectTag].x = mRandom(320)
    object[objectTag].y = mRandom(480)
    object[objectTag].name = objectTag
    print(objectTag)
    transition.to( object[objectTag], { time=2000, y=myObject.y, x=myObject.x } )
    timer.performWithDelay(2000,cleararray,1)
end
1
Attempt to call method remove self? Are you sure you don't mean removeSelf? There is a difference. - Ryan Stein
Your cleararray function is using the global objectTag which is always the id of the last object you have created. That's not going to work correctly. You need to have cleararray operate on the objectTag of the object you are timing out. - Etan Reisner

1 Answers

0
votes

cleararray meeds some way of knowing which object you want to remove. Referencing the objectTag won't work, because that's global, so it's always going have the highest value you've reached thus far, rather than the value of the object you're trying to remove. Instead, you can create a closure that references the object, so it knows what object to operate on.

local function spawnObject()
    objectTag = objectTag + 1
    object[objectTag].name = objectTag
    ...
    local function cleararray()
        object[object.name]:removeSelf()
        object[object.name] = nil
    end
    timer.performWithDelay(2000,cleararray,1)
end