This is a read-only snapshot of the ComputerCraft forums, taken in April 2020.
darkrising's profile picture

[Solved] Help sorting a table with the values inside the table

Started by darkrising, 28 November 2013 - 06:11 PM
darkrising #1
Posted 28 November 2013 - 07:11 PM
Hi, I would like to be able to sort a table by a value inside of it - not very well explained, but here's my code:


db = {
  things = {
    ["thing"] = {
      name = "bla",
      owner = "bla",
      someOtherValue = "bla",
    }
    ["another_thing"] = {
      name = "bla",
      owner = "bla",
      someOtherValue = "bla",
    }    
  }
}

ordertbl = {}

--Insert the tables from db.things into an ordered table
for name,data in pairs(db.things) do
  table.insert(ordertbl, db.things[name])
end


How would I sort the new ordertbl by things[thing].name ?
Edited on 28 November 2013 - 06:40 PM
darkrising #2
Posted 28 November 2013 - 07:39 PM
Never mind, I fixed it.


db = {
  things = {
    ["thing"] = {
      name = "bla",
      owner = "bla",
      someOtherValue = "bla",
    }
    ["another_thing"] = {
      name = "bla",
      owner = "bla",
      someOtherValue = "bla",
    }    
  }
}

ordertbl = {}

--Insert the things.thing.name into the table instead
for name,data in pairs(db.things) do
  table.insert(ordertbl, data.name)
end

--Then sort that and use it to call the data
table.sort(ordertbl)
...
Lyqyd #3
Posted 28 November 2013 - 08:30 PM
No, you should simply use table.sort correctly:


local function sortByName(first, second)
  return first.name < second.name
end

table.sort(db, sortByName)