Rect from function don't work in addEventListener

Hi everyone, I’ve got a problem :frowning:

I wrote button “class”:

-- BUTTON Button = {} function Button:new() button = {} local rect = nil; function button:add(path, x,y, w,h) rect = display.newImage(path); ... end function button:getRect() return rect; end ... return button end return Button

And then I wrote this in main file:

joy2 = Button:new(); joy2:add("media/joy2.png", 15,display.contentHeight-60, 50,50);

I want to check the joy2 is touch, so:

function joy2:getRect():touch(event) // error joy2:getRect().x = 300; end joy2:getRect():addEventListener("touch", self);

But I’ve got error: unexpected symbol near ':'

How can I do that?

First, should be

local button = {}

If this is such problem then maybe getRect() returned nil and you try to :touch(event) on that nil.

Didn’t tested but I would write it like this

Button = {} function Button:new() local button = {} button.rect = nil function button:add(path, x,y, w,h) self.rect = display.newImage(path) ... end function button:getRect() return self.rect end ... return button end return Button

and try

local rect = ​joy2:getRect() function rect:touch(event) self.x = 300 end rect:addEventListener("touch", rect) -- and to remove rect:removeEventListener("touch", rect)

Thanks! :slight_smile: But I must:

-- replace this self.x = 300; -- to rect.x = 300;

and everything works.

strange, you use :touch so ‘self’ should work because self == rect, hmmm…

Ah, self.x and rect.x works when is .touch , but only rect.x when is :touch :slight_smile:

Haha, it should be the other way :smiley: using ‘:’ gives you self and ‘.’ not :smiley:

If all is ok then do not bother, but otherwise you can also write

rect.touch = function(self, event) self.x = 300 end

First, should be

local button = {}

If this is such problem then maybe getRect() returned nil and you try to :touch(event) on that nil.

Didn’t tested but I would write it like this

Button = {} function Button:new() local button = {} button.rect = nil function button:add(path, x,y, w,h) self.rect = display.newImage(path) ... end function button:getRect() return self.rect end ... return button end return Button

and try

local rect = ​joy2:getRect() function rect:touch(event) self.x = 300 end rect:addEventListener("touch", rect) -- and to remove rect:removeEventListener("touch", rect)

Thanks! :slight_smile: But I must:

-- replace this self.x = 300; -- to rect.x = 300;

and everything works.

strange, you use :touch so ‘self’ should work because self == rect, hmmm…

Ah, self.x and rect.x works when is .touch , but only rect.x when is :touch :slight_smile:

Haha, it should be the other way :smiley: using ‘:’ gives you self and ‘.’ not :smiley:

If all is ok then do not bother, but otherwise you can also write

rect.touch = function(self, event) self.x = 300 end