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

提前感谢 :)

点赞
用户1783752
用户1783752

像 @lhf 和 @RBerteig 说的那样,问题在于 event.othernil,因此尝试访问 star 成员时会失败,尝试对空值进行索引。

假设 event.other 可能为空,解决你问题的惯用方法是在前一个 if 中添加一个空值检查 if event.phase == "began" and event.other then,因为 ifelse 条件都依赖于 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

如果你想知道关于 'attempt to index field' 的消息,你也可以在这里阅读更多关于 lua index metamethod here 的信息。

2013-10-24 00:08:10