lua-users home
lua-l archive

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

Roberto Ierusalimschy wrote:
> The point is not performance. Whenever you set a __gettable metamethod
> to a table, you cannot access that table except through a "rawget" call.

Edgar Toernig wrote:
> Like "rawset" for __newindex? ;-)

Hmm, the above statements reminded me of something.
Perhaps neither camp is 100% right or 100% wrong.  In fact maybe they are
both exactly 50% right and 50% wrong.

A __gettable metamethod is not useful to implementing "properties".  After
all if you already have a value for the property then there is no need to
generate the value via a handler function AND whatever value is stored "in
the property location" is not really the property's value anyway because it
might not be what is returned from the function.  __index on the other hand
allows both property "get" handlers AND lazy evaluation / caching schemes.

So chock one up to the "status quo" camp.  __gettable is a dud. (*)

On the other hand a "set" handler is all about triggering an action when
something tries to change the value of a property.  __newindex catches the
case in which "the user" attempts to change the value from nothing to
something, but it won't catch the case in which "the user" attempts to
change the value from something to something else.  So __newindex allows the
protection of nothing, but not the protection of something.  Furthermore you
can't even use it to be picky about what "somethings" get added because "the
user" can easily "two step" around your checks by adding an "acceptable"
value and then changing it to something "unacceptable".  __settable on the
other hand can't be "two stepped" around and it can protect all the
somethings (and the nothings as well).

So chock one up to the "new order" camp.  __newindex is a dud.

  1. __newindex is dead weight (or rather doesn't go far enough), but
__settable would be a very useful addition to Lua.
  2. __gettable would not add anything useful to Lua and __index simplifies
Lazy evaluation and allows it to operate with no continual overhead.

(*) Some might claim that __gettable, in "protecting" existing members from
read access, allows for "private" members.  In fact it does, however, the
fact that __gettable applies to the whole table rather than just specific
members means that some method must be created to distinguish "public"
members from "private" members.  Upvalues provide a much cleaner system for
implementing private members though they make things more "private" than
C++'s "private" specifier (because the values would be unreachable by other
instances of the same "type").