String compatibility error, attempt to index a nil value

2k Views Asked by At

I am using Gideros and getting this error:

    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>

I have this piece of code and as soon as the text is displayed, it gives me the above mentioned error:How can I fix this?

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
2

There are 2 best solutions below

7
Etan Reisner On

The index nil error means that on that line you are probably getting nil as a return value from LooserText:getParent().

Why you would be getting nil for that I can't tell you other than presumably because it doesn't have one.

0
Oliver On

The documentation indicates that there is no error condition for Stage.addChild except that the object added must be a Sprite. TextField inherits Sprite so there is no apparent reason for you to get this error. However, you should not re-assign the return value of delayedCall to a global variable of same name as the Timer class, this could affect other parts of the application. Since you don't use the returned Timer instance, I have removed the assignment. Also, if the stage:addChild succeeded then the removing can use stage. One thing that is strange is that your onEnter just defines youLose() but does not call it or return it, is this part of code you ommitted? In any case, you need to add some sanity checks to verify that what you think is happening is really happening w/r/t child add/remove:

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