Jump to content




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


  • You cannot reply to this topic
2 replies to this topic

#1 darkrising

  • Members
  • 234 posts
  • LocationScotland

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 by darkrising, 28 November 2013 - 07:40 PM.


#2 darkrising

  • Members
  • 234 posts
  • LocationScotland

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)
...


#3 Lyqyd

    Lua Liquidator

  • Moderators
  • 8,465 posts

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)






1 user(s) are reading this topic

0 members, 1 guests, 0 anonymous users