Lua碰撞零值

tha*_*guy 0 null lua physics collision

当我尝试执行以下代码时,它给了我这个错误:

尝试索引字段'other'(零值)

但我不知道为什么.

代码:

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
Run Code Online (Sandbox Code Playgroud)

提前致谢 :)

Gui*_*ler 5

作为@lhf和@RBerteig说,问题是event.other就是nil,让试图访问star会员未能试图指数零值.

假设event.other确实可以nil,解决问题的惯用方法是向前一个if添加一个nil检查if event.phase == "began" and event.other then,因为if和else条件都依赖于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
Run Code Online (Sandbox Code Playgroud)

如果您想知道"尝试索引字段"的消息,您还可以在此处阅读有关lua索引元方法的更多信息