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?
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
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With