user2618401
user2618401

Reputation: 3

Lua sorting tables

I know nothing about Lua, but I was able to modify a script I wanted to. I'm having troubles sorting a table though.

I've found table utils (convert table to string),
here's my table:

{{line="(Golden Aura) Challenging An owl would be either very brave or very stupid.",range="(+16 to +21)",message="(Golden Aura) Challenging An owl would be either very brave or very stupid.",colour="crimson",srt=9,keyword="owl",name="An owl"},
{line="(Golden Aura) A busy squirrel chuckles at the thought of you fighting him.",range="(+3 to +8)",message="(Golden Aura) A busy squirrel chuckles at the thought of you fighting him.",colour="gold",srt=7,keyword="squirrel",name="(Golden Aura) A busy squirrel"},
{line="(Red Aura) A parakeet should be a fair fight!",range="(-2 to +2)",message="(Red Aura) A parakeet should be a fair fight!",colour="springgreen",srt=5,keyword="parakeet",name="(Red Aura) A parakeet"},
{line="(Golden Aura) Challenging A cat would be either very brave or very stupid.",range="(+16 to +21)",message="(Golden Aura) Challenging A cat would be either very brave or very stupid.",colour="crimson",srt=9,keyword="cat",name="A cat"}}

I was able to add srt key and I want to sort a table by that. Can someone kind tell me how to do that, please?

Upvotes: 0

Views: 185

Answers (1)

Kogitsune
Kogitsune

Reputation: 415

table.sort( table:t [, function( left, right ):sorting function ] )

So, since you want to sort by v.srt, you would do something like:

table.sort( t, function( a, b ) return a.srt < b.srt end )

for k, v in pairs( t ) do
  print( v.srt, v.name )
end

Which should sort them in ascending order and then display them.

Upvotes: 4

Related Questions