lua-users home
lua-l archive

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


It seemed such a good idea at the time, `ipairs` respecting the
__index metamethod. After burning my fingers a few times with
it, though, I find it simpler not to use `ipairs` at all, instead of
pondering each time whether ipairs will behave.

Example 1. XML tables. These are lists in which the items
are either scalars or XML tables, and which also have some
"attributes", i.e. string-valued keys associated with scalar values.
The context is very often one in which the items take default
attributes from the containing value by specifying it as __index.

Unfortunately numerical keys are also inherited. If you traverse
a subtable via 'ipairs', it will look for an item in the parent table
when the subtable is exhausted. And all the way back to the
top-level table.

Example 2. Plugging holes in lists of numbers.
    x = setmetatable({5,9,nil,6,nil,nil,3,1},
    {__index = load"return 0/0",
     __len=load"return 8"})
    print(table.concat(x," "))
5 9 -nan 6 -nan -nan 3 1
Without that "index", you can't concatenate the table.

However, try this:
> for k,v in ipairs(y) do print(k,v) end
and see what happens.

If only we still had __ipairs, neat solutions to the problem
would have been possible. As it stands, the straightforward
numeric `for` is the only answer.