2016-11-06 51 views
0

我對Corona(Lua)完全陌生。運行遊戲後,遊戲似乎幾秒鐘後,當我碰到下面的錯誤,以很好地工作,直到:「試圖用數字來比較零」嘗試將零與數字進行比較Lua(Corona Lab)中的錯誤

本地函數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 = {}'中,它被定義爲模塊頂部的變量和任何函數的OUTSIDE。

local asteroidsTable = {}

感謝您的幫助!

+0

嘗試在遇到錯誤的行之前使用'print'語句。 – hjpotter92

+0

可以請你更具體一些,並給出打印聲明的例子? (對不起,我是編碼新手) – EbrahimB

回答

0

thisAsteroid.x,thisAsteroid.y,display.contentWidthdisplay.contentHeightnil

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

您還應該得到一個包含幫助您發現問題的錯誤消息的行號。

一旦找到nil值,您必須防止其變爲nil,或者如果您不能這樣做,則應將您的比較限制爲非nil值。

0

嘗試

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

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

因此,與指令table.remove(asteroidsTable)你從表中刪除asteroidsTable最後一個元素,但你應該刪除第i個元素。

瞭解更多關於從Corona forum中刪除元件的表格。