Lua - 按插入顺序打印 table 键

Lua - print table keys in order of insertion

house = {
         ["Street 22"] = {
                           {name = "George", age = 20},
                           {name = "Pete", age = 25}
                         },
         ["Street 30"] = {
                           {name = "John", age = 32},
                         }
       }

我想按照它们的确切顺序打印房屋表的 keys/streets。如果我使用:

for i, v in pairs(house) do
    print(i)
end

这将打印它们,但顺序似乎有点随机...我怎样才能按插入顺序打印它们?

Lua 表是一组键值对。没有订单。

manual 说:

The order in which the indices are enumerated is not specified, even for numeric indices.

正如 lhf 的回答已经指出的那样,仅使用 table 的关联映射部分将无法做到这一点。但是,如果使用 table 的数组索引部分维护插入顺序,则可以做到这一点。例如

table.insert(house, "Street 22")
local street = house[#house]
house[street] = { {name = "George", age = 20},
                  {name = "Pete", age = 25} }

table.insert(house, "Street 30")
street = house[#house]
house[street] = { {name = "John", age = 32} }

之后您可以使用 ipairs

将其打印出来
for _, v in ipairs(house) do
  print(v)
end