使用lua对嵌套表进行排序

我有以下表格:

{
  STANDBY = {
    timeout = "10",
    mode = "0"
  },
  RTP = {
    minport = "10000",
    maxport = "10010"
  }
}

我想按字母顺序排序,所以结果应该像这样:

{
  RTP = {
    maxport = "10010",
    minport = "10000"
  },
  STANDBY = {
    mode = "0",
    timeout = "10"
  },
}

你能帮我吗?

点赞
用户1190388
用户1190388

《Lua 程序设计》第 19.3 节中引用以下内容。

一个常见的错误是尝试对表的索引进行排序。在表中,索引形成一个集合,没有任何顺序。如果要对它们进行排序,必须将它们复制到数组中,然后对数组进行排序。

如果使用 pairs() 遍历表,则名称以任意顺序出现。但是,您无法直接对其进行排序,因为这些名称是表的键。

同一页中还提到了一个解决方法。

local tableVarName = {
    STANDBY = {
        timeout = "10",
        mode = "0"
    },
    RTP = {
        minport = "10000",
        maxport = "10010"
    }
}
function pairsByKeys (t, f)
  local a = {}
  for n in pairs(t) do table.insert(a, n) end
  table.sort(a, f)
  local i = 0      -- iterator variable
  local iter = function ()   -- iterator function
    i = i + 1
    if a[i] == nil then return nil
    else return a[i], t[a[i]]
    end
  end
  return iter
end
for name, line in pairsByKeys(tableVarName) do
  print(name, line)
end
2013-03-11 09:14:01