lua-users home
lua-l archive

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


> Yet, if we do
>
> > foo = {}
> > foo[nil]
> nil

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

The reason this doesn't emit an error is most likely due to the fact that __index can be called. I have used this in the past when I needed to store values including nil (in a set) by using a sentinel value as the key in the __(new)index method. Remember that a table lookup returning nil means the index is not present in the table so this code isn't all that surprising, even though we know nil will never index a table (directly).

If you are worried about mistyped locals not being caught, you can use a module like strict.lua to forbid undefined global access.
Luacheck also solves this problem by statically analyzing the source code, which for most things is a better alternative to a runtime guard on the environment.