在 Lua(Corona Lab)中出现尝试将 nil 与数字进行比较的错误

我对 Corona(Lua)完全不熟悉。在运行游戏后,游戏似乎完美地运作,但在几秒钟之后,我会收到以下错误:“尝试将 nil 与数字进行比较”

local function gameLoop()

-- 创建新的小行星
createAsteroid()

-- 删除已漂移到屏幕之外的小行星
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


如您在上面所看到的,'thisAsteroid' 在 'asteroidsTable = {}' 中,该变量在模块的顶部定义,并在任何函数之外。

local asteroidsTable = { }

感谢您的帮助!

点赞
用户2858170
用户2858170

以下是Markdown格式:

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.

以下是中文翻译:

如果要么 `thisAsteroid.x`、`thisAsteroid.y`、`display.contentWidth` 或 `display.contentHeight` 中有一个是 `nil`,使用 `print(thisAsteroid.x)` 等方式来找出哪个是 `nil`。

您还应该可以获取带有错误信息的行号,以帮助您找出问题所在。

一旦找到了`nil`值,您可以防止它成为 `nil`,或者如果无法防止,则应将比较限制为非 `nil` 值。
2016-11-06 09:36:33
用户7026995
用户7026995

尝试

-- 创建新的小行星
createAsteroid()

-- 移除漂出屏幕的小行星
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 文档

table.remove(list [, pos])

从 list 中移除位于位置 pos 的元素,返回所移除元素的值。当 pos 是一个介于 1 和 #list 之间的整数时,该函数将 list[pos+1]、list[pos+2]、……、list[#list] 元素向下移,然后移除 list[#list] 元素;当 #list 为 0 时 pos 还可以是 0 或 #list + 1;对于这些情况,该函数会移除 list[pos] 元素。

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

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

从 Corona 论坛 了解有关从表格中移除元素的更多信息。

2016-11-06 09:54:15