简体   繁体   中英

Random error occurs every so often: attempt to compare nil with number Corona SDK

Every so often my app will throw the following error:

gamePlay.lua:121: attempt to compare nil with number

The function moves an object from the right of the screen to the left. When it goes 50 pixels offscreen then the object should remove. Here is my code for the method:

function moveObject(self,event)

        if (self.x)<-50 then --this is line 121
            --remove object
            Runtime:removeEventListener("enterFrame", event.self)
            display.remove(event.target)

        else
            self.x = self.x-self.speed --move object left at value speed
        end
    end

The error pops up when this method is called and it goes to the restart screen:

------when ball hits another object go to restart scene------------

    local function onCollision( self,event )

        if(event.object2.name == "bonus")then--if we hit a bonus ball
            event.object2:removeSelf()

            --set score
            local currentScore =game.returnScore()
            game.setScore(currentScore*2)
            scoreText.text = game.returnScore()

            Runtime:removeEventListener("enterFrame", event.object2)

        else                

            composer.gotoScene("restart")   
            Runtime:removeEventListener("touch", onObjectTouch)    
        end
    end
    ball.collision = onCollision
    Runtime:addEventListener( "collision", ball )

Any ideas what could be happening? It is quite rarely that the error occurs, maybe 1 in 15 goes.

I think it has to do with your event listeners. I sometimes find with Corona that event listeners still run even after a scene has changed. I'm guessing that the ball is cleaned up (removed) before the event listener is stopped, and that every now and then the listener is still being run before the listener is cleaned up

To fix it, you could try

  1. removing the listener first, ball second
  2. simply adding a null check before the if check

     if (self ~= null) then if (self.x)<-50 then --this is line 121 --remove object Runtime:removeEventListener("enterFrame", event.self) display.remove(event.target) 

I've solved a similar problem by not just checking if "self" is nil, but checking if "self.x" is nil. So...

if self ~= nil and self.x ~= nil and self.x < -50 then

I'm not entirely sure why this works but I'm guessing corona is removing the display object properties and not the object itself.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM