Cast object as display.rect

Sorry for sort of cross submission but think but question has evolved (http://developer.coronalabs.com/forum/2012/08/01/there-getfillcolor#comment-118389)

I am creating a number of display.rect and adding them to a table

--array to hold all the buttons  
local btns = {};  
  
for x = 1, \_factor do  
 for y = 1, \_factor do  
  
 local btnParams = {};  
 local element = math.random(1, 5)  
 local colour = {colours[element].red, colours[element].green, colours[element].blue};  
 colourCheck[#colourCheck+1] = colour;  
 btnParams.bgColor = colourValid(#btns + 1);  
  
 btns[#btns + 1] = btnClass.newBtn(btnParams)  
 btns[#btns]:addEventListener("touch",squareBtnTapped);  
 btns[#btns].x , btns[#btns].y = (x \* \_dimension) - \_dimension, ((y \* \_dimension) - \_dimension) + \_dimension;  
 btns[#btns].xPosition = x;  
 btns[#btns].yPosition = y;  
  
 end  
end  

Then when its touched

  
function doSomething(firstObj, secondObj, xMovement, yMovement)  
  
 if(firstObj.xPosition \> secondObj.xPosition) then  
 firstObj, secondObj = secondObj, firstObj  
 firstObj:setFillColor(unpack(secondObj.getFillColor())) end  
  
end   
  
doSomething(btns[1], btns[2], 5, 5)   

I get an error of “attempt to call method ‘setFillColor’ (a nil value)”

While I can gain access to the x, y movements etc I can’t get to the methods so how do I cast the obj so its recognised as my class or display.rect to access the setFillColor to change its colour.

Am I missing something obvious? In a C language I would cast an object to its type for example var firstObj = (myObject) sender; so how do I do it in lua / Corona SDK? [import]uid: 103970 topic_id: 29533 reply_id: 329533[/import]

Disclaimer: No idea what you mean by casting

That specific error coming up means that the variable you are attempting to reference (firstObj) is not a display object (or at least not a display object that supports setFillColor()). Which in turn means (at least, based solely on the code seen) that either:

  1. btnClass.newBtn() does not return a display object, or…
  2. doSomething() operates in a place where it cannot “see” the btns[] table. (a scope issue)

The fast way to check #2 is to add this line before doSomething(btns[1]…)

print("btns[1] = ", btns[1])

If it comes up as a table, then you know btnClass is returning something, just not a display object. If it comes up nil, either btnClass is returning nothing or it’s a scope issue. [import]uid: 41884 topic_id: 29533 reply_id: 118535[/import]

@Richard awesome it was that fresh approach I needed.

In my btnClass I had added my display.rect to display.newGroup(); but it didn’t need to be so naturally didn’t have access to the setFillColor. I changed this and all is working

Thanks very much [import]uid: 103970 topic_id: 29533 reply_id: 118539[/import]

Glad you got it working! :^) [import]uid: 41884 topic_id: 29533 reply_id: 118540[/import]