Fix error of "attempt to perform arithmetic on field 'x' (a nil value)" in Corona SDK

in #programming7 years ago (edited)

Corona-image-e1499079345832.jpg

Issue Reproduce Steps

There is a widget on scene, and the widget will set value in a customised Runtime Event Listener:

  • If NO switch between scenes, the issue will not happen
  • If switch between scenes, then dispatch the customised Runtime Event Listener, this error will happen: "attempt to perform arithmetic on field 'x' (a nil value)"

How to fix

  • If you add the customised Runtime Event Listener like this:
Runtime:addEventListener("customisedEventListener", scene)
  • Then you need to remove the customised Runtime Event Listener when scene is destroyed like this:
-- destroy()

function scene:destroy( event )
  local sceneGroup = self.view
  -- Code here runs prior to the removal of scene's view
  Runtime:removeEventListener("customisedEventListener", scene)
end

Problem is solved!

问题复现

在场景上有这么一个控件,这个控件在一个自定义的运行时事件监听中会被改变值:

  • 如果不切换场景,则问题不会出现
  • 如果切换场景后,然后触发这个自定义的运行时事件监听,则会出现如下问题:"attempt to perform arithmetic on field 'x' (a nil value)"

修复方法

  • 如果你的自定义运行时事件监听如下所示:
Runtime:addEventListener("customisedEventListener", scene)
  • 那么需要在场景销毁时移除这个自定义运行时事件监听,如下所示
-- destroy()

function scene:destroy( event )
  local sceneGroup = self.view
  -- Code here runs prior to the removal of scene's view
  Runtime:removeEventListener("customisedEventListener", scene)
end

问题解决啦!

Sort:  

I upvoted you’re content I hope you’re going to check out my profile aswell I would appreciate that ;) !!

Coin Marketplace

STEEM 0.18
TRX 0.16
JST 0.030
BTC 62507.39
ETH 2451.91
USDT 1.00
SBD 2.64