I got confused too. But I did not read the lua documentation properly
(or the PiL book). Now I know.
With other languages (C, Common Lisp) I spent time reading the most
important books there are, and then using it, yet with Lua I thought
this was not needed (as much as with scheme for example).
One of the reasons I'm ignoring javascript so far, is the too many
special cases it had accumulated, and same goes for C++ to a point
(although it's my main language at work, but we tend not to use much
templates and such (just sticking to STL for basic needs)).
I actually like your suggestion for __setnew, and __getnew, but it's
probably too late to get it in.
On 4/27/2011 1:44 AM, Joseph Manning wrote:
On 2011-Apr-27 (Wed) at 10:52 (+0400), Alexander Gladysh wrote:
I often see that people do miss the fact that __index and __newindex
are called for non-existant keys only. When I was a newbie I missed
that too.
Maybe the underlying problem is that the names __index and __newindex
are poorly chosen. They seem inconsistent on two levels:
-- Compared to all other metamethod names:
Take for example __add and __concat : these apply to *all* uses
of '+' and '..'.
However, __index and __newindex apply to just *some* uses of '[ ]',
namely those for non-existent keys.
-- Amongst themselves:
Both __index and __newindex apply to 'new' (i.e. non-existent) keys,
but only one of these names contains the word 'new'.
Surely names such as __getnew and __setnew would be much clearer.
The 'get' and 'set' words make their actions much more obvious,
as classic getters and setters, and the word 'new' suggests that
they're dealing with new keys.
Also, they align better with metamethod names such as __getmetatable
and __setmetatable.
Perhaps these could be considered for future versions of Lua?
Unlike contentious issues such as tables with holes, or __ENV,
such a change would have no semantic effect whatsoever, and be
just a minimal syntactic side-step. To avoid breakage of all
exiting programs using __index and __newindex, those older names
could be kept around but deprecated; a simple find/sed script
(in *nix) could change all Lua source to use the new names.
------------------------------------------------------------------------
Joseph Manning / Computer Science / UCC Cork Ireland / manning@cs.ucc.ie
------------------------------------------------------------------------