Search code examples
luagideros

attempt to call a nil value


for i = 1, groupA:getNumChildren() do
    local sprite = groupA:getChildAt(i) 
    if cute.anim[1]:collidesWith(sprite) then
        youLoose()
    end
end

local function youLoose()
    local font3 = TTFont.new("billo.ttf", 20, " 1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ,?")
    local text7 = TextField.new(font2, "gameover")
    text7:setPosition(200, 100)
    stage:addChild(text7)
    GameLost = Bitmap.new(Texture.new("gameover.jpg"))
    Background : removeFromParent()
    groupA : removeFromParent()
    stage: addChild(GameLost)
    alert()
end

It gives an error that says 'attempt to call global youLoose (a nil value), where am I doing it wrong?


Solution

  • Note that collideswith is not the same as collidesWith; if that error you posted is correct, then you posted code that is different from what you are using. It could be that the method really is called collidesWith (it appears to be if it is the one from sprite1), but you used collideswith. Alternatively, if the code posted is what you used, then the error is likely attempt to call collideswith(a nil value), so cute.anim[1] is not a sprite1 object, but it is not nil either otherwise the error would be different.

    Once you have fixed this, you'll notice that youLoose is defined after that for loop, when you call youLoose() it is not yet defined. You're going to have to move the local function youLoose() function to before the loop. Because the loop is not itself in a function, but is at module level, it gets executed before any following code, so any functions (local or global) that are used in the loop must be defined before the loop.

    Note that "loose" does not mean the same as "lose". Check Grammar-monster to see difference. Probably everywhere you have the word "loose" you should change to "lose".