Question

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, I have a "bad argument #-2 to 'insert' (Proxy expected, got nil)" error, this is the way that I'm looking to use

Was it helpful?

Solution

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

OTHER TIPS

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

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top