Ephemeralis
Ephemeralis

Reputation: 199

Sorting lua tables by arbitrary values

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?

Upvotes: 1

Views: 692

Answers (2)

Egor Skriptunoff
Egor Skriptunoff

Reputation: 23727

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

Upvotes: 0

Martin Ender
Martin Ender

Reputation: 44259

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)

Upvotes: 4

Related Questions