Search code examples
lualua-tablecomputercraft

How to sort inner tables by value?


So, as the title says, I would like to sort a table of tables in Lua. One such example nested table is below.

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}, ...}

I would like to go through and return a table of the top ten tabl[*]['amount'] listed with their respective tabl[*]['displayName'] * being a wildcard for tabl[1.0] through tabl[max.0]

A finished table should look something like:

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

I hope this makes sense to all out there.

Link to full nested table: Full Piece FYI: I am not in control of how the table is returned to me; I got them from the function listItems() in this API.


Solution

  • So, I worked at it for a while, and thanks to community answers I came up with this piece:

    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
    

    It returned the top 10 inventories:

    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