简体   繁体   中英

Attempt to compare nil with number Error in Lua (Corona Lab)

I'm completely new to the Corona (Lua). After running the game, the game seems to work perfectly, until a few seconds later when I get the following error: 'Attempt to compare nil with number'

local function gameLoop()

-- create new asteroids
createAsteroid()

-- remove asteroids which have been drifted off the screen
for i = #asteroidsTable, 1, -1 do
    local thisAsteroid = asteroidsTable [i]

    if (thisAsteroid.x < -100 or
        thisAsteroid.x > display.contentWidth  + 100 or
        thisAsteroid.y < -100 or
        thisAsteroid.y > display.contentHeight + 100 )

    then 

        display.remove( thisAsteroid )
        table.remove( asteroidsTable)

    end

end

end


As you can see above, 'thisAsteroid' is in the 'asteroidsTable = {}' which is defined as a variable in top of the module and OUTSIDE of any function.

local asteroidsTable = { }

Thanks for your help!

Either thisAsteroid.x , thisAsteroid.y , display.contentWidth or display.contentHeight is nil .

use print(thisAsteroid.x) etc to find out which one is nil .

You should also get a line number with with the error message that helps you find the problem.

Once you have found the nil value you either have to prevent it from becoming nil or if you can't do that you should restrict your comparison to non- nil values.

Try

-- create new asteroids
createAsteroid()

-- remove asteroids which have been drifted off the screen
for i = #asteroidsTable, 1, -1 do
    local asteroid = asteroidsTable [i]

    if (asteroid.x < -100 or
        asteroid.x > display.contentWidth  + 100 or
        asteroid.y < -100 or
        asteroid.y > display.contentHeight + 100 )

    then 
        local asteroidToRemove = table.remove(asteroidsTable, i)
        if asteroidToRemove ~= nil then
            display.remove(asteroidToRemove)
            asteroidToRemove= nil
        end
    end
end
end

From lua.org documentation

table.remove (list [, pos])

Removes from list the element at position pos, returning the value of the removed element. When pos is an integer between 1 and #list, it shifts down the elements list[pos+1], list[pos+2], ···, list[#list] and erases element list[#list]; The index pos can also be 0 when #list is 0, or #list + 1; in those cases, the function erases the element list[pos].

The default value for pos is #list, so that a call table.remove(l) removes the last element of list l

So with instruction table.remove(asteroidsTable) you remove last element from table asteroidsTable but you should remove the i-th element.

Read more about removing elements from table from Corona forum .

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