对Lua table存储过程不太理解

新手上路,请多包涵
local x = {
    [1] = "a",
    [2] = "b",
    "c",
    "d",
    "e",
}


for k,v in pairs(x) do
    print(k,v)
end

为什么输出的是cde,被覆盖了key么?

阅读 4.1k
1 个回答

其实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"的原因。
你可以从这里查看原文

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进