lua-users home
lua-l archive

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


"Eric Ries" <eries@there.com>

> I've got a quick tag method question. If I've got the "index" tag method
set
> for a table (say "foo"), I can get a function called whenever someone
writes
>
> foo.member
>
> and member is nil. I can then dispatch this call based on knowledge of the
> index name (in this case the string "member").
>
> However, for the case of foo.member(bar) (or foo:member(bar)), what is the
> correct way to intercept this call? It seems to me that I lose the
> information that "someone tried to call function 'member' on table 'foo'"
if
> I use the function tag method.
>
> What is the 'correct' lua way to handle this case?

[oooh oooh I think I know this one]

Hook gettable.  You have to return a function, but it doesn't have to be a
constant function.  So:

function my_gettable(table, index)
  local v = rawget(table, index)
  if v then return v end
  -- pretend all absent values are methods to be delegated or something
  return function(self, ...)
          assert(self == %table, "tried to call method from one object on a
different object")
          print("would call", %table, "method name", %index)
  end
end

The assert is there to avoid this kind of monkey business:

  a = foo.method
  a(bar) -- self doesn't match the table where we got the method from!

BTW, I think Lua is the fastest I've ever gone from zero knowledge to
writing metaobject protocols....

Jay