lua-users home
lua-l archive

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

2009/6/10 Duncan Cross <>:
> On Wed, Jun 10, 2009 at 6:16 PM, Jerome Vuarand<> wrote:
>> It would be nice to allow nil as a key in Lua tables. I don't see any
>> syntactic or semantical reason to prevent it, and I'm sure any
>> technical reason in the Lua sources can be overcome. It would have the
>> same semantics as all other immutable values. The initial/default
>> value of the nil key would be nil. It would then be read with "t[nil]"
>> and changed with "t[nil] = value". It would be usable in a table
>> constructor as "t = {[nil] = value}". Indexing with nil would trigger
>> the __index and __newindex metamethods.
> It is quite an important sentinel value for using next() directly
> (which I do fairly often, certainly more often than I've ever felt the
> need to store a value for the nil key in a table) - next(t, nil) could
> no longer be used to fetch the first pair, and (next(t, nil) == nil)
> would no longer indicate that t is an empty table.

Actually, next wouldn't change much, it would still return nil after
having iterated over all other keys. Consider nil as being always the
last key iterated by next, rather than a supplementary sentinel. For
emptyness though you would have to test "next(t, nil)==nil and
t[nil]==nil", but only if you care about the eventual value associated
with the nil key (don't use nil as a key and you can ignore it in your
emptyness checks).

For pairs, the for loop defines that the first iteration variable (k
in "for k,v in pairs(t)") cannot be nil, so obviously the nil key
wouldn't be iterated over by pairs, unless the for loop definition is
changed. However I'm not advocating for that.

I still think being able to associate a value with a nil key can be
useful in some cases, with the limitations mentionned above. Of course
the argument about improved consistency doesn't hold anymore, unless
you consider (like I tend to do) that special cases in libraries
behaviour are less disturbing than a special case in a core language