Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to sort a table on multiple values in lua?

Tags:

sorting

lua

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?

like image 989
me2 beats Avatar asked Nov 01 '25 15:11

me2 beats


1 Answers

Variant for vararg function

function sort_on_values(t,...)
  local a = {...}
  table.sort(t, function (u,v)
    for i = 1, #a do
      if u[a[i]] > v[a[i]] then return false end
      if u[a[i]] < v[a[i]] then return true end
    end
  end)
end
like image 132
moteus Avatar answered Nov 03 '25 05:11

moteus



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!