I’m trying to figure out how I can sort a table by the name and the price, and I can’t quite figure it out. Here’s what I came up with:
local item = {}
for name, data in pairs(shopItems) do
if not table.find(inventory, name) then
if data.Price then
if typeof(data.Price) == "number" then
data.Id = name
table.insert(item, data)
end
end
end
end
table.sort(item, function(a, b)
local alphabet = a.Name > b.Name
local price = a.Price > b.Price
return alphabet and price
end)
There’s no way to do that, because it just doesn’t make any sense. A list can’t be sorted according to two metrics, because the sorted list according to metric A might not also be sorted according to metric B.
You can sort first according to one metric, and then according to another one. If two items are equal according to the second metric, then they’ll be sorted according to the first one.
You can implement it like this:
table.sort(item, function(a, b)
if a.Price == b.Price then
return a.Name > b.Name
else
return a.Price > b.Price
end
end)
Or like this:
table.sort(item, function(a, b)
if a.Name == b.Name then
return a.Price > b.Price
else
return a.Name > b.Name
end
end)
The first one sorts with price as the highest priority and name as the lowest. The second one vice versa.
EDIT: IIRC, you can also just do it like this:
table.sort(item, function(a, b) a.Price > b.Price end)
table.sort(item, function(a, b) a.Name > b.Name end)
This sorts with name as highest priority and price as lowest priority.