[Date Prev][Date Next][Thread Prev][Thread Next]
[Date Index]
[Thread Index]
- Subject: Re: Table constructor question
- From: Dirk Laurie <dirk.laurie@...>
- Date: Sat, 3 Jan 2015 18:40:38 +0200
2015-01-03 18:00 GMT+02:00 Zehao Jin <zealer_jin@163.com>:
> Hi all, there was a table constructor question confused me when I was
> testing with the following cases.
> 1.
> tb={ 'b' , [1] = 'a' }
>
> I found that tb[1] is 'b' but not 'a', I thought 'b' would be override but
> not.
> 2.
> tb = { [1] = 'a' , 'b' ,[1]='c'}
>
> I still got the tb[1]=='b' .
>
> The PIL book tells that {"r","g","b"} is equivalent to
> {[1]="r",[2]="g",[3]="b"}, so in the above cases, I
> thought tb={ 'b' , [1] = 'a' } would be translated by Lua to tb={ [1] = 'b'
> , [1] = 'a' } and tb[1] should be 'a',
> but that's wrong.
If you repeat keys in a table constructor, the order in which they are
assigned is undefined. `tb={ 'b' , [1] = 'a' }` amounts to repeating
keys. The current implementation AFAIK pushes values with
implicit keys on to the stack but assigns those with explicit keys
immediately. When you get to the end of the constructor everything
on the stack gets assigned. That's why `tb = { [1] = 'a' , 'b' ,[1]='c'}`
gives you 'b'. But you must not rely on that behaviour.