1

所以,正如标题所说,我想在 Lua 中对一张表进行排序。下面是一个这样的示例嵌套表。

tabl = {2.0={amount=281.0, meta=0.0, displayName=Dirt, name=minecraft:dirt}, 3.0={amount=190103.0, meta=0.0, displayName=Cobblestone, name=minecraft:cobblestone}, ...}

我想通过并返回列出的前十名的表格,tabl[*]['amount']其中它们各自的tabl[*]['displayName']* 是tabl[1.0]通过的通配符tabl[max.0]

完成的表格应如下所示:

sorted = {1={displayName=Cobblestone, amount=190103}, 2={displayName=Dirt, amount=281}, ...}

我希望这对所有人都有意义。

完整嵌套表格的链接:Full Piece FYI:我无法控制表格如何返回给我;我从这个API的函数listItems()中得到了它们。

4

2 回答 2

3

首先,您的数组在 语法上不正确。它应该更像:

local people = {
    {Name="Alice",Score=10},
    {Name="Bob",Score=3},
    {Name="Charlie",Score=17}
}

其次,table.sort功能应该做的工作。在我的特定示例中,它看起来这样:

table.sort(people, function(a,b) return a.Score > b.Score end)

最后,要获得顶部N只是迭代

for i = 1,N do
    print(people[i].Name, people[i].Score)
end
于 2016-04-02T04:02:52.517 回答
0

所以,我研究了一段时间,感谢社区的回答,我想出了这篇文章:

bridge = peripheral.wrap("left")
items = bridge.listItems()

sorted = {}

for i, last in next, items do
  sorted[i] = {}
  sorted[i]["displayName"] = items[i]["displayName"]
  sorted[i]["amount"] = items[i]["amount"]
end

table.sort(sorted, function(a,b) return a.amount > b.amount end)

for i = 1, 10 do
  print(i .. ": " .. sorted[i].displayName .. ": " .. sorted[i].amount)
end

它返回了前 10 个库存:

1: Cobblestone: 202924
2: Gunpowder: 1382
3: Flint: 1375
4: Oak Sapling: 1099
5: Arrow: 966
6: Bone Meal: 946
7: Sky Stone Dust: 808
8: Certus Quartz Dust: 726
9: Rotten Flesh: 627
10: Coal: 618
于 2016-04-03T21:04:09.853 回答