lua-users home
lua-l archive

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


This example was already given: Indexing a table with a variable or a
field of another table.
If the variable or field name is misspelled, you index the table with
nil and get nil, rather than an error.

That said, sometimes it is convenient because you can get away without
an explicit nil or NaN check; you can just directly index the table,
then check if the result is nil (which you probably have to do anyways).

A consequence is that (excepting metatables) indexing tables has the
nice property that it never throws:
A failed indexing operation simply returns nil. Checking for nil is more
convenient and more performant
than error handling using [x]pcall.

In other languages such as Python you have inconvenient "KeyErrors"
for failing indexing operations, so you usually have to test for
inclusion of the key in the map first,
or handle the error, or use another indexing method that doesn't throw
an error.

At least for NaN, here's another way to put it which IMO shows that it
is indeed reasonable:

NaN is defined to not equal itself. It is the only value in Lua that has
this property.

A table consists of key-value pairs (conceptually). Keys are unique.
When indexing, Lua returns the matching value given a key, or nil if
there is none. For NaN, there can not be a matching value, since
"matching" is defined as "equal", and NaN is never equal to itself.
Inserting NaNs into a table thus doesn't make sense - you wouldn't be
able to get the values out, so it'd be a memory leak per se.

For nil the choice might be considered questionable, since nil is equal
to itself in Lua. It would not be unreasonable to allow indexing tables
with nil the same way tables may be indexed with booleans.

However, recall that we use pairs to iterate over tables. pairs
internally uses next with the key as the loop control variable, and thus
next returns nil if it reaches the end of the table. If nil keys were
allowed, pairs, next, and generic for-loops would have to be more
inefficient/awkward to deal with the possibility of a nil key.

On 18.01.23 07:13, bil til wrote:
Isn't this a bit a "dispute about the emperor's beard"?

Maybe I did not understand the blogs until here very well and this has
been answered already: But can you show a short Lua example code,
where table index of nil would yield a very "unexpected / undesired /
surprising / potentially contradictory" result?