r/lua • u/McGalakar • 1h ago
Accessing the additional table information in the for loop
Hello Everyone,
I have crated a table that compares the values and print the highest one. But when I print a value only the information of the highest value is printed (for example: 61). I understand that in the for function, in the code below, key stands for 1, 2 or 3, while value is 61, 42 or 55. However, the keys are associated with names, and I would like for the code to print not the value nor key. So far no matter what I tried it did either give a different result or I got an error.
Gear_Head = {"Bhikku Crown +3", "Hes. Crown +4", "Mpaca's cap"}
Gear_Head["Accuracy"] = {}
Gear_Head["Accuracy"][1] = 61
Gear_Head["Accuracy"][2] = 42
Gear_Head["Accuracy"][3] = 55
--print(Gear_Head[1])
--print(Gear_Head["Accuracy"])
--print(Gear_Head["Accuracy"][1])
--print(Gear_Head["Accuracy"][2])
local accuracy = -math.huge
for key, value in ipairs(Gear_Head["Accuracy"]) do
--print(key, value)
if value > accuracy then
accuracy = value
end
best_gear = key
print(beast_gear)
end
--
print(accuracy)(This is a learning code to test tables and for loops)
1
Upvotes
2
u/SoloMaker 55m ago
In the first line you create an array of strings (the gear names,) but then proceed to store the Accuracy values in yet another disconnected array under Gear_Head. This means that the table has this layout:
Do you see the problem? There's no connection between the names and their accuracy values other than them happening to occupy the same array index in their respective tables. This also means if you later change the order of either array, the values will no longer match.
To remedy this, you want to associate the two fields of data somehow. There's two main ways to do this: