How to sort a table on multiple values in lua?

Viewed 1483

I need a function sort_on_values(t, ...) where ... are the variables by which the table t should be sorted. or sort_on_values(t, t_v) where t_v is a table with variables by which the table t should be sorted. Or something like that.

Function returns sorted table or sorts existing one.

Example #1:

I have a table

t = {{a=1,b=2,c=3},
     {a=1,b=1,c=2},
     {a=3,b=2,c=2}}

I do this:

t = sort_on_values(t,a,b,c)

And as result I get:

t == {{a=1,b=1,c=2},
      {a=1,b=2,c=2},
      {a=3,b=2,c=2}}

Example #2:

I do this:

t = sort_on_values(t,b,a,c)

And as result I get:

t == {{a=1,b=1,c=2},
      {a=1,b=2,c=3},
      {a=3,b=2,c=2}}

This should also work if I have a table like

t = {{a=1,b=1,c=2,d=1},
     {a=1,b=2,c=3,d=2},
     {a=3,b=2,c=2,d=3}}

And so on.

How can I do that?

2 Answers
Related