Paul Byrne
Paul Byrne

Reputation: 1615

Attempt to index global 'rectangle' (a nil value) Error

I am new to Corona, and I am trying to follow this tutorial to drag an object on screen using touch.

http://thatssopanda.com/corona-sdk-tutorials/dragging-an-object-in-corona-sdk/

I have used nearly the exact same code, with just a different name for my variable, and a rectangle instead of a circle, but I keep getting the above error.

Any ideas? The error:

(File: /Users/paulbyrne/Desktop/Transition/main.lua Line: 6

Attempt to index global 'rectangle' (a nil value)

stack traceback: [C]: ? /Users/paulbyrne/Desktop/Transition/main.lua:6: in main chunk)

    local rectangleShape = display.newRect( 100, 100, 100, 100 )
    rectangleShape:setFillColor( 255, 255, 255 )

    function rectangle:touch( event)
        if event.phase == "began" then
            display.getCurrentStage():setFocus( self, event.id)
            self.isFocus = true

            self.markX = self.x
            self.markY = self.y

        elseif self.isFocus then

            if event.phase == "moved" then
                self.x = event.x - event.xStart + self.markX
                self.y = event.y - event.yStart + self.markX
            elseif event.phase == "ended" or event.phase == "cancelled" then
                display.getCurrentStage():setFocus( self, nil )
                self.isFocus = false
            end

        end 

        return true
    end
    rectangleShape:addEventListener( "touch", rectangle )   

Upvotes: 1

Views: 3213

Answers (1)

jpjacobs
jpjacobs

Reputation: 9549

What you write is equivalent to:

rectangle.touch = function (self, event)
    ...
end

If rectangle is nil then this will fail, because you are effectively indexing nil. Personally I prefer to avoid writing function definitions using ':', as it obscures what you are effectively doing, and the input arguments (the self being hidden).

Upvotes: 2

Related Questions