[Date Prev][Date Next][Thread Prev][Thread Next]
[Date Index]
[Thread Index]
- Subject: [proposal] Using nil/NaN as table index
- From: Peter Melnichenko <petjamelnik@...>
- Date: Tue, 08 Apr 2014 20:57:26 +0400
Hello,
I think it is inconsistent that an attempt to use nil or NaN as a key when setting a field is an error:
| Lua 5.2.3 Copyright (C) 1994-2013 Lua.org, PUC-Rio
| > x = {}
| > x[nil] = "foo"
| stdin:1: table index is nil
| stack traceback:
| stdin:1: in main chunk
| [C]: in ?
...yet when getting a field it silently produces nil:
| > return x[nil]
| nil
The same happens when using rawset/rawget.
I think it is strange that trying to lookup a key which can never be set is not an error. It can easily be a source of a bug(and it was for me) if a key is mistyped or otherwise assumed to be not nil:
| foo.key = "val"
| if bar[foo.ket] then ... -- silent nil
My proposal is to make rawget(table, key) and table[key] raise errors "table index is nil/NaN" when key is nil or NaN.
Initially I thought that I could implement the idea by adding a simple check in luaH_get[1]. However, that would break __index and __newindex metamethods for nil/NaN keys: it is supposed, though only documented implicitly, that with these metamethods it is possible to use nil and NaN both when setting and getting values from a table. Circumventing this issue would probably require patching Lua in several other places.
Another solution would be to make table[nil or NaN] (no __index metamethod) raise an error, but leave rawget as it is. This can be implemented with a check in luaV_gettable[2].
Anyway, my questions:
1) Is current behaviour OK?
2) Is it useful to be able to use nil or NaN as a key when getting and setting values through metamethods?
3) Is it OK to have table[nil] raise an error but leave rawget(table, nil) returning nil?
Other thoughts?
Cheers,
Peter
[1] http://www.lua.org/source/5.2/ltable.c.html#luaH_get
[2] http://www.lua.org/source/5.2/lvm.c.html#luaV_gettable