lua-users home
lua-l archive

[Date Prev][Date Next][Thread Prev][Thread Next] [Date Index] [Thread Index]


Hi,

Have anyone tried to determine, through a metatable, whether a given table key was called as a property or called as a method?

Something like:

t = setmetatable({}, my_mt)
print(t.a)   -- one behaviour
print(t.a()) -- another behaviour

I have tried some ways, but all I could muster was this little abomination:

my_mt = {
   __lastkey = nil,
   __index = function(o, key)
      getmetatable(o).__lastkey = key   -- o.__lastkey would probably be better, but still bad
      return o
   end;
   __call = function(o, ...)
      return myfunctions[getmetatable(o).__lastkey](...)
   end;
   __tostring = function(o)
      return myfields[getmetatable(o).__lastkey]
   end;
}

I know this smells really bad, but is there any good way of doing this?

Luís Eduardo Jason Santos