[Date Prev][Date Next][Thread Prev][Thread Next]
[Date Index]
[Thread Index]
- Subject: Re: tables holding nil
- From: Matthew Wild <mwild1@...>
- Date: Thu, 23 Jul 2009 12:22:13 +0100
On Thu, Jul 23, 2009 at 12:14 PM, Kristofer
Karlsson<kristofer.karlsson@gmail.com> wrote:
>
>
> 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.
>
Myself and several other people I know would do anything for this :)
Having to check each step of a lookup is a very big pain, especially
when you have deeply-nested tables (which are common and almost
encouraged by Lua). The cleanest solution would be simply for nil[nil]
== nil, but I don't know how much that would affect other things.
> The following is already allowed:
> assert(("Hello world")[123] == nil)
>
That's simply because strings have a metatable.
> But this is not:
> assert((1234)[123] == nil)
> assert((nil)[123] == nil)
>
and numbers and nils don't :)
Matthew
- References:
- tables holding nil, Cosmin Apreutesei
- Re: tables holding nil, Jim Whitehead II
- Re: tables holding nil, Luiz Henrique de Figueiredo
- Re: tables holding nil, Cosmin Apreutesei
- Re: tables holding nil, Luiz Henrique de Figueiredo
- Re: tables holding nil, Cosmin Apreutesei
- Re: tables holding nil, Luiz Henrique de Figueiredo
- Re: tables holding nil, Kristofer Karlsson
- Re: tables holding nil, Luiz Henrique de Figueiredo
- Re: tables holding nil, Kristofer Karlsson