1

I have the following problem, somebody can help me?

comp = {}
comp.__index = function(obj,val)
  if val == "insert" then
    return rawget(obj,"gr")["insert"]
  end
  return rawget(obj, val)
end

comp.new = function() 
  local ret = {} 
  setmetatable(ret, comp) 
  ret.gr = display.newGroup()
  return ret
end
local pru = comp.new()
pru.gr:insert(display.newImage("wakatuBlue.png"))

This line works, but I don't want to access the insert method using the gr property, I want to call the insert method directly and the metatable __index function does the work

pru:insert(display.newImage("wakatuBlue.png"))

This line doesn't work and I get this error: "bad argument #-2 to 'insert' (Proxy expected, got nil)", but this is the way that I'm looking to use

Michael M.
  • 10,486
  • 9
  • 18
  • 34
cbeltrangomez
  • 412
  • 2
  • 9

2 Answers2

2

Do you want something like this?

comp = {}
comp.__index = function(obj,val)
  if val == "insert" then
    return rawget(obj,"gr"):insert(val)
  end
  return rawget(obj, val)
end
tprk77
  • 1,151
  • 1
  • 9
  • 22
0

__index works just fine; it's because your last call is interpreted as:

pru.insert(pru, display.newImage("wakatuBlue.png"))

whereas you want/need it to be:

pru.insert(pru.gr, display.newImage("wakatuBlue.png"))

You either need to call it like this or explain what you are trying to do.

Paul Kulchenko
  • 25,884
  • 3
  • 38
  • 56
  • I wonder why the error is that argument #-2 is nil, when it should be `pru` which isn't nil (just not a Proxy). – Omri Barel Jan 20 '13 at 02:18
  • It's because Corona detects Proxy as a table with a field `_proxy` that points to some userdata. If you add `_proxy = {}` to `pru`, you will get a different error ("Proxy expected, got table"). – Paul Kulchenko Jan 20 '13 at 02:55