lua-users home
lua-l archive

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

Where this thread seems to be headed is toward defining a standard userdata
type "array".

    a = array( 2, nil, "foo" )

    #a -- yields 3

    a:insert( "baz" )

    a[ 4 ] -- yields "baz"

    a:unpack() -- yields 2, nil, "foo", "baz"

    for i, v in a:ipairs() do
        print( i, v )
        -- 1    2
        -- 2    nil
        -- 3    foo
        -- 4    baz

Not that hard to define. Probably built by using the environment table for
the userdata perhaps with a separate metatable per object as well that can
point to the environment table in its __index entry.

Of course, now we've moved from one table to three in order to represent an
array and we've lost the simple uniformity of having only one data type. So,
I'm not sure it's an improvement.

The fundamental problem with the current situation is that code that isn't
savvy about nil as a hole will probably mostly work unless someone writes a
unit test that specifically tries to make it fail or unless we run into a
case in the field where we get a nil. That makes code a lot less reliable
than it ought to be.

I'm still pondering the solution, but I'm thinking that it probably involves
going back to something like treating "n" or some other key specially in
tables. Actually, I'm thinking # could be interesting as in something like:

    { 2, nil, "foo", # }
    { #, f() }
    { #, ... }

Of course, this still essentially creates two different data types since we
have tables and tables with length.