Associatively sorting a table by value in Lua

You seem to misunderstand something. What you have here is a associative array. Associative arrays have no explicit order on them, e.g. it’s only the internal representation (usually sorted) that orders them.

In short — in Lua, both of the arrays you posted are the same.

What you would want instead, is such a representation:

items = {
    {1004, "foo"},
    {1234, "bar"},
    {3188, "baz"},
    {7007, "quux"},
}

While you can’t get them by index now (they are indexed 1, 2, 3, 4, but you can create another index array), you can sort them using table.sort.

A sorting function would be then:

function compare(a,b)
  return a[1] < b[1]
end

table.sort(items, compare)

Leave a Comment