1

I have a Lua table in the following form:

tTest = {}

tTest.word1 = {
                IsOnline = true,
                UpdateTime = 2,
                Value = 150
              }
tTest.word2 = {
                IsOnline = true,
                UpdateTime = 1,
                Value = 25
              }
tTest.word3 = {
                IsOnline = true,
                UpdateTime = 1,
                Value = 1000
              }

I want to iterate through this table with the highest Value first. So I tried this

for k,v in pairs(tTest, function(a,b) return a.Value > b.Value end) do
    print (v.Value)
end

But it's not displaying the Values sorted.

Any help would be appreciated, thanks.

hjpotter92
  • 78,589
  • 36
  • 144
  • 183
Wallboy
  • 154
  • 5
  • 14
  • 1
    possible duplicate of [How to loop through the table and keep the order?](http://stackoverflow.com/questions/24714253/how-to-loop-through-the-table-and-keep-the-order) – Deduplicator Jul 27 '14 at 01:37

1 Answers1

2

If you can control your structure, design the table like:

tTest = {
  {
    "word1",
    IsOnline = true,
    UpdateTime = 2,
    Value = 150
  },
  {
    "word2",
    IsOnline = true,
    UpdateTime = 1,
    Value = 25
  },
  {
    "word3",
    IsOnline = true,
    UpdateTime = 1,
    Value = 1000
  }
}

and, now you can sort the table as:

table.sort( tTest, function(u,v) return u.Value > v.Value end )

If you can't control the source table; create a temporary table:

local t = {}
for k, v in pairs(tTest) do
    t[ #t + 1 ] = v
    table.insert(t[#t], k)
end

and then use the table.sort function with same logic as above on this local table t.

hjpotter92
  • 78,589
  • 36
  • 144
  • 183
  • Thanks, I chose creating the temporary table option as I would have do some significant rewriting of some other code to use your changed structured of my table. Also I noticed I made the mistake of thinking the sorting function was a pairs() argument instead of the table.sort() function. I got it all working now. One other question, would it also be possible to sort my table structure by it's key? – Wallboy Jul 27 '14 at 01:51
  • 1
    @Wallboy You'll still have to create the temporary table and use appropriate logic inside the `table.sort` callback. Instead of `u.Value > v.Value`, it'd be: `u[1] > v[1]` instead. – hjpotter92 Jul 27 '14 at 01:55
  • @Wallboy That _is_ another question but see this [answer](http://stackoverflow.com/a/15706820/2226988). – Tom Blodget Jul 27 '14 at 01:55
  • @hjpotter92 u[1] > v[1] works perfect to sort by key! Thanks. I also noticed I could just add another field into the table that has the same value as the key and just sort by that. But since u[1] > v[1] works great, I'll just use that. Thanks again! – Wallboy Jul 27 '14 at 02:01