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)

As Komel said, you're dealing with associative arrays, which have no guaranteed ordering.

If you want key ordering based on its associated value while also preserving associative array functionality, you can do something like this:

function getKeysSortedByValue(tbl, sortFunction)
  local keys = {}
  for key in pairs(tbl) do
    table.insert(keys, key)
  end

  table.sort(keys, function(a, b)
    return sortFunction(tbl[a], tbl[b])
  end)

  return keys
end

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

local sortedKeys = getKeysSortedByValue(items, function(a, b) return a < b end)

sortedKeys is {1234,3188,1004,7007}, and you can access your data like so:

for _, key in ipairs(sortedKeys) do
  print(key, items[key])
end

result:

1234     bar     
3188     baz     
1004     foo     
7007     quux