gpt4 book ai didi

sorting - 使用lua对嵌套表进行排序

转载 作者:行者123 更新时间:2023-12-02 11:13:14 26 4
gpt4 key购买 nike

我有下表:

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

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

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

你能帮我吗?

最佳答案

引用以下内容:Programming in 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. However, you cannot sort them directly, because these names are keys of the table.

同一页面上还提到了解决方法。

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

关于sorting - 使用lua对嵌套表进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15334417/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com