Lua - 对 table 中的嵌套数组进行排序
Lua - Sorting nested array within a table
我在 Lua 中有一个 table,其中包含如下数组:
lines =
{
{"red", "blue", "green", "yellow"},
{1,4,3,2}
}
我需要按第二个数组的顺序对 table 进行排序,因此它最终如下所示:
lines =
{
{"red", "yellow", "green", "blue"},
{1,2,3,4}
}
我正在尝试像下面那样使用 table.sort,但这似乎是想将字符串与 int 进行比较:
table.sort(lines, function (a, b)
return a[2]<b[2]
end)
我该怎么做?
你做得不好。
函数 table.sort(list, comp)
对给定 table 的元素进行排序,而您正在对 lines
table 进行排序,因此“排序”您拥有的两个 table彼此而不是一个一个排序,正确的方法应该是:
table.sort(lines[1])
table.sort(lines[2])
假设您要向列表中添加更多 table 将是:
for _, v in ipairs(lines) do
table.sort(v)
end
编辑:
这是真正的解决方案:
local new = {}
for i, v in ipairs(lines[2]) do
new[i] = lines[1][v]
end
lines[1] = new
按通常方式对第二行进行排序
然后根据第二行在第一行设置正确的顺序
local lines = {
{"red", "blue", "green", "yellow"},
{1,4,3,2}
}
local tmp = {}
for j = 1, #lines[2] do
tmp[lines[2][j]] = lines[1][j]
end
table.sort(lines[2])
for j = 1, #lines[2] do
lines[1][j] = tmp[lines[2][j]]
end
我在 Lua 中有一个 table,其中包含如下数组:
lines =
{
{"red", "blue", "green", "yellow"},
{1,4,3,2}
}
我需要按第二个数组的顺序对 table 进行排序,因此它最终如下所示:
lines =
{
{"red", "yellow", "green", "blue"},
{1,2,3,4}
}
我正在尝试像下面那样使用 table.sort,但这似乎是想将字符串与 int 进行比较:
table.sort(lines, function (a, b)
return a[2]<b[2]
end)
我该怎么做?
你做得不好。
函数 table.sort(list, comp)
对给定 table 的元素进行排序,而您正在对 lines
table 进行排序,因此“排序”您拥有的两个 table彼此而不是一个一个排序,正确的方法应该是:
table.sort(lines[1])
table.sort(lines[2])
假设您要向列表中添加更多 table 将是:
for _, v in ipairs(lines) do
table.sort(v)
end
编辑: 这是真正的解决方案:
local new = {}
for i, v in ipairs(lines[2]) do
new[i] = lines[1][v]
end
lines[1] = new
按通常方式对第二行进行排序
然后根据第二行在第一行设置正确的顺序
local lines = {
{"red", "blue", "green", "yellow"},
{1,4,3,2}
}
local tmp = {}
for j = 1, #lines[2] do
tmp[lines[2][j]] = lines[1][j]
end
table.sort(lines[2])
for j = 1, #lines[2] do
lines[1][j] = tmp[lines[2][j]]
end