lua-users home
lua-l archive

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


Lua's indexing mechanism works this way:

1. If rawget(tbl,i) is not nil, then tbl[i] is just another way to
   get it, and tbl[i]=a does the same as rawset(tbl,i,a).
2. If rawget(tbl,i) is nil, then tbl[i] will use __index or __newindex
   if available.

Now consider the scenario where the designer of a table plans to allow
only certain keys. If all those keys are given values to start with, the
__index and __newindex methods can just throw errors.

However, it may happen that only some values are assigned when the table
is created. One could either give some sentinel value to the others (but
we've just had quite a long thread which demonstrated that people are
not agreed on whether this is a good idea), in which case the simple
error-throwing __index and __newindex metamethods still work, or one
can do something clever with those metamethods.

One approach is to have a prototype table in which all possible legal
keys have values. Then setting `__index` to that table will return those
default values, and if nil is still returned by `tbl[i]`, we know that
`i` is not an approved key. `__newindex` could be something like

    function(tbl,k,v)
       if tbl[k] then rawset(tbl,k,v) else error"..." end
    end

i.e. __newindex exploits the mechanism created for __index, if any.

Now comes my question. That prototype table: should it be weak? Does
the answer depend on whether the prototype may appear in more than one
metatable?