4

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 2

4

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
Sign up to request clarification or add additional context in comments.

Comments

1

Generic code for this task will probably take some work but you can start with this:

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

function sort_on_values(t,a,b,c)
    table.sort(t, function (u,v)
        return
             u[a]<v[a] or
            (u[a]==v[a] and u[b]<v[b]) or
            (u[a]==v[a] and u[b]==v[b] and u[c]<v[c])
    end)
end

sort_on_values(t,"a","b","c")
for i=1,#t do
    print(i,t[i].a,t[i].b,t[i].c)
end

1 Comment

Wow cool thanks! Seems to work. But what if I have "d", "e" etc? Ideally, I would like to have a more general solution. It seems more difficult to implement. But thanks anyway)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.