I am currently working on a shop for my game, but i need some objects in a table to be sorted by price.
I currently have a dictionary named items
local Items = {}
In the items dictionary i add the items with a for loop:
for _,v in pairs(FolderName:GetChildren()) do
Items[v.Name] = {
["Price"] = v.Price.Value,
["Asset"] = v,
["ValueType"] = v.ValueType.Value
}
end
But when i do it like this i get a result that looks something like this:
So how do i sort the items in the dictionary
1 Like
I believe table.sort() would work well here:
As per Lua specification, table.sort works as follows:
table.sort(Table t, Predicate p = default)
The object t is a Lua table you want sorted, and p is an optional Lua function you can pass for doing the comparisons.
sort iterates over all the items in t and runs p(a, b) on them. p returns true if a should come before b. The table is sorted in place, so t can be modified after the call to sort.
If you don’t provide a function for the p argument, a default is used, which behaves something lik…
1 Like
I tried to use the table.sort() but it still gave me the same output
This is what i tested:
table.sort(Items, function(a,b)
return a["Price"] < b["Price"]
end)
1 Like
colbert2677
(ImagineerColbert)
March 16, 2020, 5:49pm
#5
Maybe you don’t want to sort the items out. table.sort is primarily for sorting arrays. If you have something like a UIListLayout , then you can set the LayoutOrder of your items frames to a certain value: for example, if you’re sorting by price, you can use the price as the LayoutOrder of the frame and it will automatically sort from least to greatest priced item.
5 Likes
rokec123
(rok)
March 16, 2020, 5:55pm
#6
That’s what I did and it seems to work just fine. Basically what I’m doing is:
Define another table
Loop through the dictionary and insert each object into a table using table.insert function
Sort the table
Loop through the table using numerical for loop
local items = {
item1 = {
price = 5
};
item2 = {
price = 2
};
item3 = {
price = 1
};
item4 = {
price = 4
};
item5 = {
price = 3
};
}
local tab = {}
for i, v in pairs(items) do
table.insert(tab, v)
end
table.sort(tab, function(a,b) return a.price > b.price end)
for i = 1,#tab do
print(tab[i].price) --> 5 4 3 2 1
end
3 Likes
ImAvafe
(Avafe)
August 14, 2020, 11:37pm
#7
How would you automate the making of the table “items”?
I have a folder with items inside containing a price value. It would be easier if I didn’t have to write the “items” table out.