2013-10-23 19 views
0

當我試圖執行下面的代碼它給我這個錯誤:Lua的碰撞零值

Attempt to index field 'other' (a nil value)

,但我不知道爲什麼。

代碼:

function onCollision(event) 
if event.phase == "began" then 
    if event.other.star == "star" then 
     score = score + 1 
    elseif event.other.mine1 == "mine1" then 
     if jet.collided == false then 
     timer.cancel(tmr)  
     jet.collided = true  
     jet.bodyType = "static" 
     explode() 
     end 
    end 
    end 
end 

感謝提前:)

+5

這意味着'event.other'爲零的消息。 – lhf

+3

什麼lhf說。這意味着傳遞給'onCollision'的值是一個表(或者像一個),但它沒有名爲'other'的字段。也許該字段實際上被命名爲「其他」。或許'onCollision'還沒有通過你認爲它的對象。 – RBerteig

回答

5

由於@lhf和@RBerteig說,問題是event.othernil,所以試圖訪問star成員沒有試圖指數爲零值。

假設event.other確實可以nil,解決你的問題是,如果if event.phase == "began" and event.other then無利可圖檢查添加到以前的,因爲兩者如果和其他條件取決於event.other要設置的慣用方式。

function onCollision(event) 
if event.phase == "began" and event.other then 
    if event.other.star == "star" then 
     score = score + 1 
    elseif event.other.mine1 == "mine1" then 
     if jet.collided == false then 
     timer.cancel(tmr)  
     jet.collided = true  
     jet.bodyType = "static" 
     explode() 
     end 
    end 
    end 
end 

如果你想知道關於「企圖索引字段」你也可以閱讀更多有關lua index metamethod here