lua-users home
lua-l archive

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




On Thu, Jul 23, 2009 at 1:03 PM, Luiz Henrique de Figueiredo <lhf@tecgraf.puc-rio.br> wrote:
> Are there any use cases where allowing reading t[nil] or t[nan] is useful?

t[nil] is what happens when you do t[x] and x is nil :-)

Yes, obviously :-)
 

This may or not be a programmer error: you may be trying to determine
whether a field given by the user exists in a table. If the user does
not define the name of that field, then it's nil and you get t[nil].
Not too common an idiom, though.

That may be a valid use case I suppose.
How about chaining table lookups like this:

heightmap = {{1,2,3},{4,5,6}}

local value = heightmap[1][4]
local value = heightmap[3][4]

In the first case, it will return nil, since the y value is out of range.
In the second case it would throw an error (tried to index nil).

Couldn't the same reasoning be applied here, and change table lookups to return nil if the table itself was nil? (But throw an error when setting)
This would mean that heightmap[x][y] would return nil instead of erroring, and it would give somewhat more consistency.

The following is already allowed:
assert(("Hello world")[123] == nil)

But this is not:
assert((1234)[123] == nil)
assert((nil)[123] == nil)