简体   繁体   English

用lua排序嵌套表

[英]Sort nested table with lua

I have following table: 我有下表:

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

I want to sort it alphabetically, so the resulting table should be something like this: 我想按字母顺序对它进行排序,因此结果表应该是这样的:

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

Can you please help me? 你能帮我么?

Quoting the following from Programming in Lua : 19.3 . 在Lua编程中引用以下内容:19.3

A common mistake is to try to order the indices of a table. 一个常见的错误是试图对表的索引进行排序。 In a table, the indices form a set, and have no order whatsoever. 在一个表中,索引形成一个集合,并且没有任何顺序。 If you want to order them, you have to copy them to an array and then sort the array. 如果要订购它们,则必须将它们复制到数组中,然后对数组进行排序。

If you traverse a table with pairs() , the names appear in an arbitrary order. 如果使用pairs()遍历表,则名称将以任意顺序出现。 However, you cannot sort them directly, because these names are keys of the table. 但是,您不能直接对它们进行排序,因为这些名称是表的键。

The workaround is also mentioned on the same page. 在同一页面上也提到了解决方法。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM