lua-users home
lua-l archive

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


On Jul 1, 2013 2:05 PM, "Roberto Ierusalimschy" <roberto@inf.puc-rio.br> wrote:
>
> > Couldn't a lot of ambiguity and unexpected behavior avoided by keeping
> > nil but introducing two new functions to the table library called
> > "table.has(t,key)" and "table.delete(t,key,[to])" - and dropping the
> > deletion via assigning nil?
>
> At last something new and worth a discussion. Does anyone see problems/
> incompatibilities/etc. with this?
>
> (But what is "[to]"?)
>
> Keep in mind that #t would still be undefined for arrays with holes,
> but holes would be much less frequent...
>
> -- Roberto
>

This seems like a good idea, but I feel like it might complicate the internals a bit. Are you proposing that nil is able to be stored in tables, and keys can be removed only by table.delete()? (In that case, why is #t still undefined when holes are present? Or are nil keys no longer holes?) That could be useful, but also a bit confusing as it means a key set to nil and a key that was never set (or was deleted) are different things, but both have a nil value.

Personally I was always fond of the method used in previous versions (and that seems to be making a comeback with table.pack) - treat "array" as a special case of table. An array would have a field "n" telling how many elements are in it. Then iterating, inserting, deleting etc would just be from 1 to n regardless of the contents. (You could even still add or clear elements manually as long as you take care to keep n up to date.) In other words, it's table.getn/setn, but with n being an ordinary field in the table rather than a special attribute that can only be accessed through helper functions.

This could already be done without any changes to the language by an 'array' module, though that still leaves table.remove, table.insert etc which could be a bit confusing. (Such a module could also offer the ability to set a metatable that would "magically" keep n up to date, or leave you to manage it yourself.)

Although I feel like this is a new topic entirely - the original question was about having keys with nil values, and I'm not sure whether that refers to integer keys in the middle of an array, or named keys - the solutions differ. The OP had mentioned wanting to be able to map a database column to a Lua table transparently and needing a portable, standardized "null but not nil" value to store in those tables to indicate that the column exists but has a value of null in that row.