lua-users home
lua-l archive

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


Using nil to index a table can be useful sometimes.

While the manual states that you cannot use nil or NaN as a table index it also states that any key that is not part of the table is associated with nil.

Consequently foo[nil] must resolve to nil because key nil can never be part of the table.

Am Di., 17. Jan. 2023 um 11:59 Uhr schrieb Aki Tuomi <cmouse@cmouse.fi>:
Hi!

I am looking at an odd behaviour of Lua tables with nil index.

Lua documents for tables says

   An associative array is an array that can be indexed not only with numbers, but also with strings or any other value of the language, except nil.

Yet, if we do

> foo = {}
> foo[nil]
nil

it works. Why? This sounds like this should emit error?

The reason this matters is that it is too easy to do errors with nil indexes, like when using named indexes from modules:

values[module.IDX_FOR_VALUE] = nil if there is no IDX_FOR_VALUE in module.

$ lua -v
Lua 5.3.3  Copyright (C) 1994-2016 Lua.org, PUC-Rio

Kind regards,
Aki Tuomi