Having trouble with removing object if it to far from an object?

Hey I’m having trouble removing a object when it far from an object. Basically what I have is if the ball is more than 200 units away from object is destroyed I got that working with code below is the whole entire code

[code]local object = display.newRect(100, 100 , 100, 100)

local ball = display.newCircle(100, 300 , 10, 10)

local function move ()
object.x = object.x + 1
end
timer.performWithDelay(1, move, -1)

local distLimit = 200

local function checkFrame(event)
if (math.abs(object.x - ball.x)) > distLimit then
–the two objects are now too far apart
–destroy
display.remove(ball)
end
end
Runtime:addEventListener(“enterFrame”,checkFrame) [/code]

The problem is when the object is more than 200 units away from the ball I get an error in the terminal saying

Runtime error
/Users/sebitttas/Desktop/Test/main.lua:13: attempt to perform arithmetic on field ‘x’ (a nil value)
stack traceback:
[C]: ?
/Users/sebitttas/Desktop/Test/main.lua:13: in function
?: in function <?:215>

I don’t understand this error. Anyone please help really appreciated

:slight_smile:
[import]uid: 17058 topic_id: 21427 reply_id: 321427[/import]

When you get the error has the ball already been removed? Is so you should change your function to something like this:

[code]

local function checkFrame(event)
if ball ~= nil then
if (math.abs(object.x - ball.x)) > distLimit then
–the two objects are now too far apart
–destroy
display.remove(ball)
end
end
end
[/code] [import]uid: 23649 topic_id: 21427 reply_id: 84849[/import]

@jeremyapplebaum12 Yes I get the error when the ball is removed, and I’m still getting the error for the code you gave me [import]uid: 17058 topic_id: 21427 reply_id: 84850[/import]

Weird, I thought display.remove or object:removeself automatically set it’s self to nil upon completion.

Anyway I tested this and it works:

[code]

local function checkFrame(event)
if ball ~= nil then
if (math.abs(object.x - ball.x)) > distLimit then
–the two objects are now too far apart
–destroy
ball:removeSelf()
ball = nil
end
end
end
[/code] [import]uid: 23649 topic_id: 21427 reply_id: 84856[/import]

@jeremyapplebaum12 Thanks a lot it works like a charm :slight_smile: [import]uid: 17058 topic_id: 21427 reply_id: 84859[/import]