Search code examples
luaselfmetatable

Lua Metatables - calling functions with colon syntax


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


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