【问题标题】:Attempt to compare nil with number Error in Lua (Corona Lab)尝试将 nil 与 Lua 中的数字错误进行比较(Corona Lab)
【发布时间】:2017-03-19 17:38:17
【问题描述】:

我对 Corona (Lua) 完全陌生。运行游戏后,游戏似乎运行良好,直到几秒钟后我收到以下错误:'Attempt to compare nil with number'

本地函数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

结束


正如您在上面看到的,“thisAsteroid”位于“asteroidsTable = {}”中,它被定义为模块顶部和任何函数外部的变量。

本地小行星表 = { }

感谢您的帮助!

【问题讨论】:

  • 尝试在遇到错误的行之前使用print 语句。
  • 您能否更具体一些并举例说明打印语句? (对不起,我是编码新手)

标签: lua coronasdk


【解决方案1】:

thisAsteroid.xthisAsteroid.ydisplay.contentWidthdisplay.contentHeight 中的任何一个都是 nil

使用print(thisAsteroid.x) 等找出哪个是nil

您还应该获得一个带有错误消息的行号,以帮助您找到问题。

找到nil 值后,您要么必须阻止它变为nil,要么如果不能这样做,则应将比较限制为非nil 值。

【讨论】:

    【解决方案2】:

    试试

    -- 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
    

    来自 lua.org documentation

    table.remove(list [, pos])

    从列表中删除位置 pos 的元素,返回值 被移除的元素。当 pos 是 1 和 #list 之间的整数时,它 向下移动元素 list[pos+1], list[pos+2], ···, list[#list] 并删除元素列表[#list]; #list 时索引 pos 也可以为 0 为 0,或#list + 1;在这些情况下,函数会擦除元素 列表[位置]。

    pos 的默认值为#list,因此调用 table.remove(l) 会删除列表 l 的最后一个元素

    因此,使用指令 table.remove(asteroidsTable) 您从表 asteroidsTable 中删除最后一个元素,但您应该删除第 i 个元素。

    详细了解如何从 Corona forum 中删除表格中的元素。

    【讨论】:

      猜你喜欢
      • 2017-03-06
      • 2016-04-22
      • 1970-01-01
      • 2022-01-11
      • 1970-01-01
      • 1970-01-01
      • 2021-10-13
      • 2018-07-31
      • 1970-01-01
      相关资源
      最近更新 更多