lua-users home
lua-l archive

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



On 27-Feb-07, at 10:55 AM, Jerome Vuarand wrote:

Rici Lake wrote:
On 26-Feb-07, at 7:31 PM, Graham Wakefield wrote:
Yes, I've been trying this approach today; mapping __index and
__newindex metamethods of the userdata to the userdata environment
table. A disadvantage of this is that in Lua my object behaves as a
table for general use, but not as a table for functions such as
table.foreach() and generic for, which could be confusing for end
users.  Is there a way to implement a next() method for the generic
for construction?

The main issue with implementing this in Lua is not efficiency (even
table.foreach isn't bad). The problem is that the metatable might
(quite reasonably) be locked with a __metatable key, and that would
prevent us from actually getting at the __pairs pseudo-metamethod.
Implementing it in C avoids that problem.

Actually people securing userdata metatables can set the __metatable
field to a table instead of just false or some locking value, and then
expose __pairs (and eventually other) metamethod(s) to Lua. Since pairs
is meant to be a helper to manipulate the userdata it's normal to make
it available to code manipulating that userdata.

Yes, that is certainly an alternative, and probably even good style.
Still, it seems to me that it would not be a bad idea to replace the
existing C implementation of pairs() with a version which respects
a potential __pairs() metamethod using the semantics indicated in
my Lua implementation. I can't really see the downside; the slight
extra overhead of the __pairs() lookup only happens during loop
setup, so it's not going to be noticeable in normal programs.