1

I have a table with the following structure:

table = {
    [1] = {"something", "high"}
    [2] = {"something else", "low"}
    [3] = {"something further", "medium"},
    [4] = {"yet more something", "medium"},
}

What I want to do, is to use a delegate function to sort that table with table.sort() so that the priority variable (high, low, medium, etc) orders the list with high being followed in the list, followed by medium and then low. How would I go about doing this?

2 Answers 2

4

You seem to know how table.sort works, so where are you stuck? Simply create a lookup table that translates priority names into integers and compare those:

priorities = {high = 2, medium = 1, low = 0}
table.sort(t, function(e1, e2)
    return priorities[e1[2]] > priorities[e2[2]]
end)
Sign up to request clarification or add additional context in comments.

Comments

0
table.sort(t, 
  function(e1, e2)
    return e1[2]:sub(-1) < e2[2]:sub(-1)
  end
)

3 Comments

Funny idea, but quite obscure and inflexible, don't you think?
I just wanted to add a note of caution, as this is a very compact solution but one that I don't think should go into production code ;)
@Ephemeralis - Please don't embed my solution into production code :-)

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.