local x = {
[1] = "a",
[2] = "b",
"c",
"d",
"e",
}
for k,v in pairs(x) do
print(k,v)
end
为什么输出的是cde,被覆盖了key么?
其实TABLE的构造,官方文档在2.5.7 Table Constructors 已经给出。
Table constructors are expressions that create tables. Every time a constructor is evaluated, a new table is created. A constructor can be used to create an empty table or to create a table and initialize some of its fields. The general syntax for constructors is
tableconstructor ::= `{´ [fieldlist] `}´
fieldlist ::= field {fieldsep field} [fieldsep]
field ::= `[´ exp `]´ `=´ exp | Name `=´ exp | exp
fieldsep ::= `,´ | `;´
Each field of the form [exp1] = exp2 adds to the new table an entry with key exp1 and
value exp2. A field of the form name = exp is equivalent to ["name"] = exp. Finally,
fields of the form exp are equivalent to [i] = exp, where i are consecutive numerical integers, starting with 1.
最后一句, 类似于 exp 的形式将以table[idx]的形式开始,idx从1开始。
这就是为什么会覆盖[1]="a",[2]="b"的原因。
你可以从这里查看原文