lua-users home
lua-l archive

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


Am 01.08.2014 14:56 schröbte Jean-Luc Jumpertz:
Moving this to a new thread to avoid polluting the Lua 5.3.0 (alpha) announcement.

Le 1 août 2014 à 14:41, Philipp Janda <siffiejoe@gmx.net> a écrit :

And btw testing the  '__len' and '__index'  metamethods in function 'luaB_ipairs' has an almost null performance cost and gives you additional flexibility, so what would it bring to restrict this test to the '__len' metamethod, as Philipp Janda proposed? :-)

It's useless code that causes one extra case of undefined behavior, so why keep it? And what's the additional flexibility?

The additional flexibility is to allow you to freely define the values you want to return for table[i] and to keep it consistent between direct accesses like << a = my_table[i] >> and for loops like << for i, v in ipairs(my_table) >>, even if you don't redefine __len

As I argue above, you can't. `__index` without `__len` is either superfluous ( `__index` never gets called) or highly unpredictable (undefined behavior, could stop in mid-loop in current Lua implementation).

Can you elaborate on this? I really can not get your point here...

`__index` is only called when you encounter a nil value. If you encounter a nil value, your array has holes. If your array has holes its length is not defined. Without `__len` you can't have both: Either your `__index` function is called or `luaL_len` computes a deterministic length.


It looks to me that  `__index` without `__len` would be appropriate in the case of an indirection-typed data structure, where the value returned by __index is based on the raw value stored in the table and preserves the nil table entries. Which is not an uncommon pattern.


The value returned by `__index` can't be based on the raw value, because there is no raw value or else `__index` wouldn't be called in the first place. Nevertheless, a data structure with `__index` but without `__len` makes perfect sense -- just not for the current `ipairs` behavior.


Philipp