Is there something that would do the same thing as table.sort, but backwards?
Asked
Active
Viewed 1,655 times
1
-
2Does this answer your question? [sorting a table in descending order in Lua](https://stackoverflow.com/questions/6726130/sorting-a-table-in-descending-order-in-lua) – mrjamaisvu Jun 28 '22 at 08:58
-
Have you take a look at [this post](https://stackoverflow.com/questions/6726130/sorting-a-table-in-descending-order-in-lua)? – mrjamaisvu Jun 28 '22 at 08:59
-
4Do you want to _"sort a table in reverse order"_ or _"just reverse the items in a table"_? Those are completely different things. – Zakk Jun 28 '22 at 09:22
2 Answers
0
The table.sort function allows you to define a sorting function as the second argument. It returns a boolean and specifies the order on which the table must be ordered:
local atable = {1,2,3}
table.sort(atable, function(a,b) return a > b end)
for _, v in pairs(atable) do
print(v)
end
--[[This prints:
3
2
1
]]
Of course, this doesn't limit itself to "lists" but you can use them on other table types as well:
local cityInfo = {
{name = "Vancouver", population = 321, location = "Canada"},
{name = "Paris", population = 123, location = "France"},
{name = "London", population = 1000, location = "United Kingdom"},
}
table.sort(cityInfo, function(a,b) return a.population > b.population end) -- Here the items are ordered in descencing order based on the population field
for _, v in pairs(cityInfo) do
print(v.population)
end
--[[This prints:
1000
321
123
]]

user19433446
- 1
- 1
-
"Of course, this doesn't limit itself to "lists" but you can use them on other table types as well" - this is plain wrong. `table.sort` **is literally limited to the list part of the table**. Your first table is a "list" of primitive values (numbers) whereas your second table is a "list" of tables. Both are lists. – Luatic Jun 28 '22 at 09:49
0
If you want to sort a table in reverse order:
table.sort(your_table, function(x, y) return x > y end)
If you want to reverse a table:
local function reverse(tab)
for i = 1, #tab//2, 1 do
tab[i], tab[#tab-i+1] = tab[#tab-i+1], tab[i]
end
return tab
end

Zakk
- 1,935
- 1
- 6
- 17