Hello,
I am currently writing a modulescript that holds a Table of Dictionaries of purchasable hats for my game. The dictionaries include the price of the hat and I want to place the buttons to buy the specified hats into a GuiList in the PlayerGui from lowest price to highest price. However, obviously ipairs doesn’t work with dictionaries so I’m a little stuck on how I would go about doing this.
Here’s an example of the Table:
I was able to use normal pairs to place all the buttons into the Gui so that isn’t the problem, I just need them placed in order by price. Any help is appreciated.
You can use table.sort to organise based on the price.
For example:
local hats = {
hat_tophat = {
price = 2
},
hat_glasses = {
price = 1
}
}
table.sort(hats, function(a,b)
return a["price"] < b["price"]
end)
for i, v in pairs(hats) do
print(v["price"])
end
I’m still a little confused because I am not familiar with table.sort, it seems to have only put them in order when they’re out of order in the first place when I tried it. For example,
Sorry for the confusion, that function only works on arrays. In this case you would have to add all of the dictionary prices into an array and sort it from there:
local hats = {
hat_tophat = {
price = 2
},
hat_glasses = {
price = 100
},
hat_other = {
price = 20
},
hat_scarf = {
price = 1
}
}
local array = {}
for key, value in pairs(hats) do
array[#array+1] = {value = value["price"]}
end
table.sort(array, function(a, b)
return a.value < b.value
end)
for i, v in ipairs(array) do
for i, v in pairs(v) do
print(v)
end
end
Many thanks! This does work, however I was wondering if there’s a way I can keep the name of the hat (which was the key for the values in the Dictionary table) as the Index in the Array table?