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.

1

1 Answer 1

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.

4
  • 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
    Commented Jul 27, 2014 at 1: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
    Commented Jul 27, 2014 at 1:55
  • @Wallboy That is another question but see this answer. Commented Jul 27, 2014 at 1: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
    Commented Jul 27, 2014 at 2:01

Not the answer you're looking for? Browse other questions tagged or ask your own question.