Search code examples
lua

Lua key conflict with array index


I am a newbie two lua. Recently I learned about Table in lua.

In my view (I am not sure whether it is right), table can be used as Array as well as Map. When used as Map, values without keys automatically get ordinal index.

t1 = {"a", "b"}
t2 = {"a", [2] = "b"}

It is true for both t1 and t2 that tX[1] == "a" and tX[2] == "b", where X is 1 or 2.

It get confusing when automatically assigned index and named key are in conflict, which is

t3 = {"a", [1] = "b"}

in this case t3[1] == "a" and t3[2] == nil. and no warns or errors were arose.

I guessed "b" may overwrite "a" in index 1, but it is not. So what is the principle in this situation ?

Lua keeps the flexibility of TABLE structure. Though this gives table much more possiblity and capability, it also involves some confusion. What's the main notion of such design ?


Solution

  • Refer to Reference Manual: 3.4.9 - Table Constructors; you are interested in:

    Fields of the form exp are equivalent to [i] = exp, where i are consecutive integers starting with 1; fields in the other formats do not affect this counting.

    and:

    The order of the assignments in a constructor is undefined. (This order would be relevant only when there are repeated keys.)