gpt4 book ai didi

lua - 对表数组进行排序

转载 作者:行者123 更新时间:2023-12-04 21:45:54 25 4
gpt4 key购买 nike

这可能比我自己做更容易。我对 Lua 比较陌生,但对其他语言有经验。

我有一张看起来像这样的表:

local state = {}
state[1] = {
show = true,
changed = true,
progressType = "static",
value = 0,
total = 9,
name = "nine",
}

state[2] = {
show = true,
changed = true,
progressType = "static",
value = 0,
total = 7,
name = "seven",
}

state[3] = {
show = true,
changed = true,
progressType = "static",
value = 0,
total = 8,
name = "eight",
}

state[4] = {
show = true,
changed = true,
progressType = "static",
value = 0,
total = 6,
name = "six",
}

我需要做的是对每个进行排序 table[]基于 table.value5 的值的条目.我在文档中找不到任何明确说它们不仅仅是基本的功能 table.sort所以我发现自己有点卡住了。我是否需要通过迭代并使用排序数据创建新表来手动排序?

最佳答案

I can't find any functions in the docs that expressely say they do more than just a basic table.sort so I find myself a bit stuck.



我可能误解了您的问题,但是 table.sort在这种情况下正是您所需要的:

local state = {}
state[1] = {
total = 9,
name = "nine",
}

state[2] = {
total = 7,
name = "seven",
}

state[3] = {
total = 8,
name = "eight",
}

state[4] = {
total = 6,
name = "six",
}

-- Use table.sort with a custom anonymous function
-- to specify how to compare the nested tables.
table.sort(state, function (a, b)
return a.total < b.total
end)

for i=1, #state do
print(i, state[i].name)
end

table.sort您可以提供一个可选的自定义函数,它可以随您的需要简单或复杂。在这种情况下(根据您的问题)只需比较 total 就足够了。表的值。

关于lua - 对表数组进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60228366/

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