字符串兼容性错误,尝试索引一个空值。

我在使用Gideros时遇到了以下错误:

    main.lua:47: attempt to index a nil value
stack traceback:
    main.lua:47: in function 'func'
    [string "compatibility.lua"]:36: in function <[string "compatibility.lua"]:35>

我有这段代码,只要文本显示,就会给我上述错误。我该如何修复?

function onEnter()
    function youLoose()
    local font2 = TTFont.new("billo.ttf", 20, "1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ")
    LooserText = TextField.new(font2, "You Loose   , Try AGAIN?")
    LooserText:setPosition(100, 100)
    stage:addChild(LooserText)
    Timer = Timer.delayedCall(1000, removing)
    end --line 36
   end
    function removing()
    LooserText:getParent():removeChild(LooserText)  --line 47
    end
点赞
用户258523
用户258523

index nil 错误意味着在那一行中,LooserText:getParent() 的返回值可能是 nil

我无法告诉你为什么会得到 nil,但很可能是因为它没有父级。

2014-05-14 16:59:15
用户869951
用户869951

文档指出,Stage.addChild 没有除了要添加的对象必须是 Sprite 之外的错误条件。TextField 继承自 Sprite,因此你不应该出现这个错误。然而,你不应该将 delayedCall 的返回值重新分配给同名的全局变量 Timer 类,否则可能会影响应用程序的其他部分。由于你没有使用返回的 Timer 实例,我已经删除了这个分配语句。此外,如果 stage:addChild 成功,那么 removing 可以使用 stage。一个奇怪的事情是,你的 onEnter 只是定义了 youLose(),但没有调用它或返回它,这是你省略的代码部分吗?无论如何,你需要添加一些健全性检查来验证你认为正在发生的事情确实正在发生,特别是对于子项的添加和移除:

function onEnter()
    function youLoose()
        local font2 = TTFont.new("billo.ttf", 20,   "1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ")
        LoserText = TextField.new(font2, "You Lose   , Try AGAIN?")
        LoserText:setPosition(100, 100)
        print('Stage num children:' .. stage:getNumChildren())
        stage:addChild(LoserText)
        print('Stage num children:' .. stage:getNumChildren())
        print('LoserText is stage child #' .. stage:getChildIndex(LoserText))
        Timer.delayedCall(1000, removing)
     end
end

function removing()
    print('Stage num children:' .. stage:getNumChildren())
    print('LoserText is stage child #' .. stage:getChildIndex(LoserText))
    stage:removeChild(LoserText)
    print('Stage num children:' .. stage:getNumChildren())
end
2014-05-15 01:28:08