Help resolve this error

  • error received (comparing number to nil value)
  • two functions
  • one run-time event listener

– The below function is called in my create method and runs properly displaying an apple with a listener to call the removeBody function

      local function spawn()

          apple = display.newImage(“apple.png”)

          apple.x = 50

          apple.y = 200

          apple.enterframe = removeBody

          RunTime:addEventListener(“enterFrame”, apple)

          sceneGroup:insert(apple)

      end

 ***Note the apple is continuously rolling to the right I just didn’t add that code***

–This next function is where my error occurs. Its goal is to remove the apple once the apple rolls past an (x value) of 200

     local function removeBody(self, event)

          if (self.x > 200) then

               self:removeSelf()

          end

          return true

     end

–The  Error states that my self.x value above is a nil value and is compared to a number. I can’t figure out why it’s nil. The self passed into the  removeBody function should be the global variable apple so why isn’t self.x being initialized to the apples current x value and then removed once it reaches 200?

local function removeBody(self, event) if( not self.removeSelf ) then return end -- If not valid, skip if (self.x \> 200) then Runtime:removeEventListener( "enterFrame", self ) display.remove(self) end end
  1. If you don’t remove the listener, the enterFrame gets called even after the removal.
  2. Use display.remove() instead of obj:removeSelf() – The latter is unsafe

Please use code formatting next time, and you should make that apple a local too.

local function spawn() local apple = display.newImage("apple.png") apple.x = 50 apple.y = 200 apple.enterframe = removeBody RunTime:addEventListener("enterFrame", apple) sceneGroup:insert(apple) return apple end

Thank you been trying to solve this for 2 days now :smiley:

local function removeBody(self, event) if( not self.removeSelf ) then return end -- If not valid, skip if (self.x \> 200) then Runtime:removeEventListener( "enterFrame", self ) display.remove(self) end end
  1. If you don’t remove the listener, the enterFrame gets called even after the removal.
  2. Use display.remove() instead of obj:removeSelf() – The latter is unsafe

Please use code formatting next time, and you should make that apple a local too.

local function spawn() local apple = display.newImage("apple.png") apple.x = 50 apple.y = 200 apple.enterframe = removeBody RunTime:addEventListener("enterFrame", apple) sceneGroup:insert(apple) return apple end

Thank you been trying to solve this for 2 days now :smiley: