示例:
table1 = {2,3,1}
table2 = {a,b,c}
到
table1 = {1,2,3}
table2 = {c,a,b}
答案 0 :(得分:6)
此函数不会修改任何一个表,并返回根据第一个表排序的第二个表。您可以在第一个表中传递键的比较,例如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
答案 1 :(得分:3)
我会:
第1步:将两个表合并为{{2,a},{3,b},{1,c}}
第2步:对对进行排序。
步骤3:取消合并生成的数组。
table1 = {2,3,1}
table2 = {"a","b","c"}
-- Comparison function
function compare(x, y)
return x[1] < y[1]
end
-- Step 1: Merge in pairs
for i,v in ipairs(table1) do
table1[i] = {table1[i], table2[i]}
end
-- Step 2: Sort
table.sort(table1, compare)
-- Step 3: Unmerge pairs
for i, v in ipairs(table1) do
table1[i] = v[1]
table2[i] = v[2]
end
for i = 1,#table1 do
print(table1[i], table2[i])
end
答案 2 :(得分:1)
我使用键值对和常规排序函数来完成这项工作:
table1 = {2,3,1}
table2 = {"a","b","c"}
table3 = {}
for i, v in ipairs(table2) do
table3[table1[i]] = v
end
table.sort(table1)
table2 = {}
for i = 1,#table1 do
table2[i]=table3[table1[i]]
end
table3=nil
for i = 1,#table1 do
print(table1[i], table2[i])
end
答案 3 :(得分:0)
尝试使用标准函数table.sort
:
table1 = {2,3,1}
table2 = {"a","b","c"}
table3 = {}
for i,v in ipairs(table1) do
table3[table2[i]]=v
end
table.sort(table1, function (a,b)
return table2[a] <= table2[b]
end)
table.sort(table2, function (a,b)
return table3[a] <= table3[b]
end)
print("table1")
for i,v in ipairs(table1) do
print(i,v)
end
print("table2")
for i,v in ipairs(table2) do
print(i,v)
end