lua-users home
lua-l archive

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


2016-07-01 6:09 GMT+02:00 Philipp Janda <siffiejoe@gmx.net>:
> Am 01.07.2016 um 03:01 schröbte Jonathan Goble:
>>
>> The fact that this thread has ballooned into nearly 80 emails and is
>> still being debated suggests to me that perhaps we need to stop trying
>> to make tables do a job that they weren't designed to do, and instead
>> create a new array type separate from tables that is designed to do
>> that job.

> One could add a table subtype (much like the integer subtype for numbers)
> and stick the size field to the end of the table structure like the payload
> for a userdata. This way we could re-use most of the table implementation.
> In fact, arrays would behave exactly like regular tables except when
> array-like behavior conflicts with generic table-like behavior.

I like the basic idea, but we don't really need an explicit subtype, just
a specialized standard table. See below.

> Of course the `#` operator (and as a consequence the `table` functions)
> should raise an error when applied to a non-array table without `__len` ...

But breaking almost every existing Lua program just because its author
was not clairvoyant would be going too far.

The desired effect can be achieved by one function in the standard library.
That's all.

Well, actually two, since the second one is useful for any OOP.

~~~~
table.array(tbl[,n])

Sets or modifies the metatable of tbl so that #t always equals n,
__index points to the table library, and t:type() returns "array".
If n is not supplied, it is calculated from the current tbl so that
#tbl+1 is the first key absent from the table. Returns tbl.

table.type(tbl)

Returns the __name field in the metatable of tbl.
~~~~

The following matters would be implementation details.

1. How __len does it. (A field in the Table structure? An entry
keyed by tbl in the registry?)
2. Whether tbl is exempt from compaction when having more
than 50% holes.
3. Whether tbl would if necessary be resized so that the 'array'
part has size at least n.
4. Whether the table functions would exploit the optimizations
possible if #t is not greater than the size of the 'array' part.