Just_Hash
Just_Hash

Reputation: 11

attempt to index local 'on' (a nil value)

I can't see why this is giving me an error. I am starting on programming so it could be so embarrassing. It's a reusable button that's giving me a hard time. On line 12 where I try to change the on alpha ii gives me the error.

local Button = {}
Button.new = function(params)
local btn = display.newGroup()

local offIMG = params and params.off or "off.png"
local onIMG = params and params.on or "on.png"

local off = display.newImageRect("offIMG", 64, 70)
local on = display.newImageRect("onIMG", 100, 100)
on.alpha = 0

btn:insert(off)
btn:insert(on)

btn.x = params and params.x or 0
btn.y = params and params.y or 0

function btn:touch(e)
    if(e.phase=="began")then
        on.alpha = 1
        display.getCurrentStage():setfocus(self)
        self.hasFocus = true
    elseif (self.hasFocus) then
        if(e.phase=="ended")then
            on.alpha = 0
            display.getCurrentStage():setfocus(self)
            setfocus(nil)
        end
    end
end

btn:addEventListener("touch",btn)

return btn

end

local button1= Button.new()
button1.x = display.contentWidth * 0.5
button1.y = display.contentHeight * 0.5

Upvotes: 1

Views: 2258

Answers (1)

Etan Reisner
Etan Reisner

Reputation: 80992

Assuming by line 12 you mean on.alpha = 0 that means the problem is that the function call in the previous line local on = display.newImageRect("onIMG", 100, 100) is not returning a value as you expect and is instead returning nil. I suspect this is the case because you are passing the string "onIMG" as the first argument instead of passing the variable onIMG as the first argument as it seems you meant to do.

Try local on = display.newImageRect(onIMG, 100, 100) and a similar change for the offIMG line above that and see if that helps.

Upvotes: 4

Related Questions