Wallboy
Wallboy

Reputation: 154

Trouble sorting this Lua Table

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.

Upvotes: 1

Views: 158

Answers (1)

hjpotter92
hjpotter92

Reputation: 80657

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.

Upvotes: 2

Related Questions