This function does not modify any of the tables, but returns a second table, sorted according to the first. You can pass the comparison for the keys in the first table, for example, to table.sort.
local sort_relative = function(ref, t, cmp)
local n =
assert(
local r = {}
for i=1,n do r[i] = i end
if not cmp then cmp = function(a, b) return a < b end end
table.sort(r, function(a, b) return cmp(ref[a], ref[b]) end)
for i=1,n do r[i] = t[r[i]] end
return r
end
For instance:
local table1 = {2, 3, 1}
local table2 = {"a","b","c"}
local sorted = sort_relative(table1, table2)
print(table.unpack(sorted))
leads to:
c a b
source
share