例: table1 = {2,3,1}table2 = {a,b,c} 至 table1 = {1,2,3}table2 = {c,a,b} 此函数不会修改任何一个表,并返回根据第一个表排序的第二个表.您可以在第一个表中传递键的比较,就像在table.sort中一样. l
table1 = {2,3,1}
table2 = {a,b,c}
至
table1 = {1,2,3}
table2 = {c,a,b}
此函数不会修改任何一个表,并返回根据第一个表排序的第二个表.您可以在第一个表中传递键的比较,就像在table.sort中一样.
local sort_relative = function(ref, t, cmp)
local n = #ref
assert(#t == n)
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
例如:
local table1 = {2, 3, 1}
local table2 = {"a","b","c"}
local sorted = sort_relative(table1, table2)
print(table.unpack(sorted))
结果是:
c a b
