【问题标题】:Lua collision nil valueLua 碰撞 nil 值
【发布时间】:2013-10-24 08:08:10
【问题描述】:

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

尝试索引字段“其他”(零值)

但我不知道为什么。

代码:

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

提前致谢:)

【问题讨论】:

  • 表示event.other为nil。
  • lhf 所说的。这意味着传递给onCollision 的值是一个表(或类似表),但它没有名为other 的字段。也许该字段实际上被命名为Other。也许onCollision 没有传递你认为它拥有的对象。

标签: lua physics collision null


【解决方案1】:

正如@lhf 和@RBerteig 所说,问题是event.other 是nil,因此尝试访问star 成员无法尝试索引零值。

假设event.other 确实可以是nil,解决问题的惯用方法是在前面的 if if event.phase == "began" and event.other then 上添加一个 nil 检查,因为 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

如果您想知道“尝试索引字段”的消息,您还可以阅读有关lua index metamethod here的更多信息

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-03-13
    • 2017-06-09
    • 1970-01-01
    • 2014-03-14
    • 2021-12-13
    • 1970-01-01
    • 2017-08-24
    • 2015-02-09
    相关资源
    最近更新 更多