lua-users home
lua-l archive

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

Is it better to have 20 different workarounds to a common problem than one simple, clear, language supported fix?

If you want arrays with holes, there are basically only three different workarounds:

1.  use nil for the holes
    pro: - saves memory for very sparse arrays
         - fits well with varargs and table.(un)pack.
         - no mapping from hole to nil required
    con: - needs explicit length field
         - needs metatable if you want `#` and `ipairs` to work

2.  use a sentinel value for holes
    pro: - can use `#` and `ipairs` without metatable magic
    con: - cannot handle large sparse arrays
         - does not mix well with {...} and table.pack( ... )

3.  use some specialized container class/object
    pro: - can't be mistaken for a raw table
         - can implement whatever policy you see fit
    con: - does not feel like a raw table

Actually I think if 1. would become part of the standard library it wouldn't be a workaround.

Lets assume there would be a sparse array library. It would not replace the current one, as the current is maybe good for some uses (I hardly use it myself to be honest).

The new "array" library would always use a metatable to store the length and would not use a sentinel. This new library defines __len and __ipairs etc.

What I suggest, is to actually use solution 1. but make it official. To make it official would avoid the chaos of different implementations.

I would prefer this solution as it it solves the problem you have at the very point where it appears, in the array. If you introduce an "empty" type you have to expect that this empty type will pop up at all the other places within the language. And why solution 1? It's the only solution that is able to story any values and lets one use the array type as a normal table.