lua-users home
lua-l archive

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


Hi,

Mark Hamburg wrote:
> What is the expected behavior if one indexes a table with a nil key? I had
> thought it was to throw an exception. In fact I feel I've seen an exception
> get thrown but maybe not. Now, however, I seem to be getting back nil.

Lua 4.x did not allow this. Lua 5.x does.

> The manual says that nil is an illegal key.

But this only means that a table cannot hold a nil key. This does
not imply anything about indexing behaviour.

Well, there's pseudo-code for index and newindex in the Lua 5.1
manual in section "2.8 Metatables". But it relies on the
definitions of rawget() and rawset().

Looking there, the description for rawget() does not match the
implementation. rawget(t, nil) just returns nil and does not
raise an error.

> I certainly prefer the definition that says that t[ nil ] is always equal to
> nil for any valid table. I just didn't realize that was the case.

I guess some existing Lua 5 code depends on this, too.

Another quirk: __index is called for nil keys, but __newindex is
not called before the error is raised (mentioned before on the
list). The latter behaviour does not match with the pseudo-code.

I guess this is the old problem with language definition vs.
implementation behaviour. There's no alternative implementation
of Lua 5.x, so there was never a need for a clear separation.

Bye,
     Mike