DisplayObjects and Metatables

I’m working up a quick prototype and during one of the recent changes I swapped out a TextObject for a GroupObject containing a TextObject and a DisplayObject. Because I fancied being ‘clever’ I figured that rather than updating all the code where I refer to a TextObject’s text field, I could instead give the group a metatable, catch all calls to the text field and pass them on to the TextObject. 

Here’s the code:

[lua]

      scene.bank=display.newGroup()

      scene.view:insert(scene.bank)

      scene.bank.isVisible=false

      local text=display.newText({

        parent=scene.bank,

        text=0,

        fontSize=40,

      })

      local bg=display.newImage(scene.bank,“img/blurbox.png”)

      text:toFront()

      local mt={__newindex=function(t,k,v) 

        if k==“text” then

          text.text=v

          return

        end

        rawset(t,k,v)

      end,

      __index=function(t,k) 

        if k==“text” then

          return text.text

        end

        return rawget(t,k)

      end

      }

      setmetatable(scene.bank,mt)

[/lua]

It works fine, except that setting the GroupObject’s isVisible (and presumably other fields) no longer works. Am I doing this wrong or are the rawset and rawget functions breaking the GroupObject implementation? I had a quick look in the documentation and there’s nothing about rawset and rawget in the documentation’s gotchas.

Hi.

Basically, groups already have a metatable, so just setting a new one stomps on that and you lose the properties implemented by that.

I gave some of the details for that here, and develephant recommended some other options, too. This one might have some useful points, too.

Thanks, I had a feeling that might be it. It would be good if the official documentation was updated to explain this

Hi.

Basically, groups already have a metatable, so just setting a new one stomps on that and you lose the properties implemented by that.

I gave some of the details for that here, and develephant recommended some other options, too. This one might have some useful points, too.

Thanks, I had a feeling that might be it. It would be good if the official documentation was updated to explain this