I have an array with all the attributes of a part. I will be using them later on but for now I wish to sort them into the same order as the materials array. I just can’t work out the logic, sometimes I get back the exact same table assortment and other times returns nothing. It shouldn’t be this hard but I’m getting frustrated now and not thinking clearly.
Entries to tables with non-numeric keys have no “order” to speak of.
In Lua/Luau, tables have two partition: array and dictionary/hashtable. You can only sort values in array portion, which must have key-value pairs with numeric keys. However, in table2
your keys are strings, which means they are stored on the dictionary partition, which doesn’t have a concept of “order” because that’s not how they work by design.
May I ask why your data has to be ordered that way specifically? Maybe we could work out a better solution from there.
You can “sort” the table by converting it into a numeric array instead:
local numeric = {}
for _, material in pairs(materials) do
table.insert(numeric, table2[material])
end
print(numeric[1]) --amount of logs
print(numeric[2]) --amount of food
--etc
Also to answer your question, no you can’t sort a dictionary. That’s because dictionaries as a data type aren’t meant to be looped over(like arrays/lists). That’s because they have known and specific keys(for example Coins, Speed, etc).
Well Idk if ordering it is the best way. I will have a lot of buttons (tree-of-life) style game and I made one button. I added a lot of attributes that the game will use and I was working on the textlabels for all buttons. This way I can add any number of buttons and the script should set up all the textlabels with the correct cost, resources and rewards displayed. I figured ordering the table would make it easier to select different amounts of resources (tier1 requires logs, tier 2 requires logs and stone, tier 3 requires 3 resources) etc.
Then I can just loop through all the buttons in that tier and let the script set all the textlabels. Also with table2 set via table1 I can move the data around in table1 till I’m happy with the order . The script should set the labels correctly regardless of the order I set table1 to.
As stated, dictionaries don’t really have an order. You look it up by key. But, you can create a paired table with a specific order of you want. Like if table1 does exist, you can loop through table 1 and index into table 2 with the value from table 1.
for _, name in pairs(table1) do
print(table2[name])
end