lua-users home
lua-l archive

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


On this day of 09/19/07 20:38, Duck saw fit to scribe:
> The manual simply says that "the construction
> 
>       for k,v in pairs(t) do _body_ end
> 
> will iterate over all key-value pairs of table t."
> 
> Whilst might been seem as implying that only k-v pairs actually in table t 
> will be returned (i.e. no metamethods pursued), it doesn't explicitly say 
> so (perhaps it should?).

I think it has to do with how you conceive of the 'index' operation. An
index metamethod isn't adding keys to a table: it's a trap used to
handle a key not existing in the table. As such, when pairs/ipairs
traverse the table, they only touch keys that are actually present.


> So my question is: why do pairs and ipairs (and, by implication, next) 
> behave this way?

One reason might be that it would be confusing if pairs iterated over
keys that were in fact present and keys that are present in the __index
table of the metatable, but it didn't iterate over keys that were
handled by an __index function. Of course, pairs has no way of knowing
which keys an __index function might handle. But then you have a
situation where 'metakeys' (if I may) are handled in some cases but not
others. So to answer your question, it might be in part to avoid this
kind of undesirable situation.

Cheers,
- David

-- 
~David-Haley
http://david.the-haleys.org