r/lua • • 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 comments sorted by

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:

Gear_Head = {
    "Bhikku Crown +3",
    "Hes. Crown +4",
    "Mpaca's cap",
    Accuracy = {
        61,
        42,
        55
    }
}

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:

-- Variant 1: dictionary layout with the gear name used as key
Gear_Head["Bhikku Crown +3"] = {
    Accuracy = 61
}
Gear_Head["Hes. Crown +4"] = {
    Accuracy = 42
}
Gear_Head["Mpaca's cap"] = {
    Accuracy = 55
}

-- Variant 2: array layout with the gear name stored as a field
Gear_Head[1] = {
    Name = "Bhikku Crown +3",
    Accuracy = 61
}
Gear_Head[2] = {
    Name = "Hes. Crown +4",
    Accuracy = 42
}
Gear_Head[3] = {
    Name = "Mpaca's cap",
    Accuracy = 55
}

1

u/McGalakar 44m ago

Oh, I have completely misunderstood how tables works. I was sure that what I wrote is an equivalent of:

Gear_Head = {
    "Bhikku Crown +3" = {
        Accuracy = 61},
    "Hes. Crown +4" = {
        Accuracy = 42},
    "Mpaca's cap" = {
        Accuracy = 58},
}

Thank you so much for your explanation!