簡體   English   中英

嘗試在Lua中將nil和Number Error進行比較(Corona實驗室)

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

我是Corona(Lua)的新手。 運行游戲后,游戲似乎運行良好,直到幾秒鍾后出現以下錯誤:“嘗試將nil與數字進行比較”

局部函數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 = {}”中,它被定義為模塊頂部的變量,且位於任何函數的外部。

局部小行星表= {}

謝謝你的幫助!

thisAsteroid.xthisAsteroid.ydisplay.contentWidthdisplay.contentHeightnil

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

您還應該獲得帶有錯誤消息的行號,以幫助您發現問題。

一旦找到nil值,就必須防止它變為nil或者如果不能這樣做,則應將比較范圍限制為非nil值。

嘗試

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

table.remove(列表[,pos])

從列表中刪除位置pos上的元素,返回已刪除元素的值。 當pos是1到#list之間的整數時,它將下移元素list [pos + 1],list [pos + 2],...,list [#list]並擦除元素list [#list]; 當#list為0或#list + 1時,索引pos也可以為0。 在這種情況下,該函數將刪除元素列表[pos]。

pos的默認值為#list,因此調用表。remove(l)刪除列表l的最后一個元素。

因此,使用指令table.remove(asteroidsTable)可以從表asteroidsTable刪除最后一個元素,但是應該刪除第i個元素。

在Corona 論壇上了解有關從表中刪除元素的更多信息。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM