Home > Mobile >  Lua - Sorting nested array within a table
Lua - Sorting nested array within a table

Time:05-05

I have a table in Lua that contains arrays like follows:

lines = 
{
    {"red", "blue", "green", "yellow"},
    {1,4,3,2}
}

I need to sort the table in order of 2nd array so it ends up like the following:

lines = 
{
    {"red", "yellow", "green", "blue"},
    {1,2,3,4}
}

I'm trying to use table.sort like below, but this seems to want to compare the string to an int:

table.sort(lines, function (a, b)
  return a[2]<b[2]
end)

How do I do this?

CodePudding user response:

Sort the second line the usual way
and after that set the correct order in the first line according to the second line

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

CodePudding user response:

You are doing it bad. The function table.sort(list, comp) orders the elements of the given table and you are sorting the lines table, so is "sorting" the two tables you have with each other instead of sorting each one, the correct way should be:

table.sort(lines[1])
table.sort(lines[2])

Assuming you will add more tables to your list would be:

for _, v in ipairs(lines) do
    table.sort(v)
end
  • Related