1

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 )   

1 Answer 1

2

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).

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, I had just realised that function rectangle:touch ... is not declaring a function called rectangle but referring to the rectangle object.I agree it is clearer to write out the line longhand. Many thanks.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.