Search code examples
lua

"attempt to index a nil value"-error in Lua


function newImage(Image, posx, posy)
    pic = Bitmap.new(Texture.new(Image))
    stage:addChild(pic)
    pic:setPosition(posx,posy)
end

local birdie = newImage("bird.png", 100, 100)
birdie:setAnchorPoint(0.5,0.5)
birdie:setRotation(45)

If I call newImage() like above, the image gets loaded but when I try to use birdie:setAnchorpoint() it gives the error "attempt to index birdie, a nil value".
How can I fix this?


Solution

  • You're not returning anything from your function call. Also, use local variables inside functions.

    function newImage(Image, posx, posy)
        local pic = Bitmap.new(Texture.new(Image)) 
        stage: addChild(pic)
        pic:setPosition(posx,posy)
        return pic
    end