As dictionary keys are not integers, they cannot be sorted. Arrays, however, have integer keys, giving them an order. So, there are multiple ways of ordering your item table:
1. Get rid of item name:
If the item name isn't required, you can simply do this:
Items = {
50,
200,
100
}
Which will give a sorted table when you iterate through it.
2. Have your item details in dictionaries in an array:
If you're item names do matter, you could instead do this:
Items = {
{
Name = "Item1",
Price = 50
},
{
Name = "Item2",
Price = 200
},
{
Name = "Item3"
Price = 100
}
}
To iterate throgh this table, you can then do:
for _,Item in pairs(Items) do
print(Item.Name, Item.Price)
end
which would print them in order.
3. Use two tables:
Alternatively, you could have one dictionary for the item details and one dictionary for the names:
ItemDetails = {
["Item1"] = 50,
["Item2"] = 200,
["Item3"] = 100
}
local Items = {"Item1","Item2","Item3"}
You could then iterate through this by going:
for _,ItemName in pairs(Items) do
local ItemPrice = ItemDetails[ItemName]
print(ItemPrice)
end
Which will print it in the order of the Items table, however you have to enter each item name twice.
Hope this helps!
1 comment
Sorting a dictionary inherently doesn't make any sense, due to the way they're stored in memory. https://scriptinghelpers.org/questions/60697/why-does-the-table-not-printing-in-logical-order#59068 for an explanation.