To get the value of “Damage” or “Heal” from the table using a string, you can simply use the square bracket notation with the string as the key. For example, if the variable name contains the name of the hero you want to access and string contains either “Damage” or “Heal”, you can retrieve the corresponding value like this:
local value = heroes[name][string]
If string contains “Damage” and name contains “Archer”, for example, the value of value will be 2. Similarly, if string contains “Heal” and name contains “Builder”, the value of value will be 25
Generally you would use a for loop for this purpose as assigning the index to a variable doesnt give you the name of the index, It more of gives you to Value of that said index, so ifd I did this:\
Tab = {
["indexKey"] = "value"
}
print(Tab["indexKey"]) --> value
IT would Return the value rather than the index, with the usage of for loops, you can 2 Arguments (or whatever they are called.
The First is index which is name of the index holding the value
The Second is value which is the Instance, number, or boolean it contains.
So with this, you can do a simple search of the table using this for loop to get their names.
for index, value in Tab do
-- index is the name of the key
-- value is the value of the index
end
local heroes = {
["Archer"] = {Damage = 2},
["Fire Wizard"] = {Damage = 5},
["Builder"] = {Heal = 25},
["Gunner"] = {Damage = 1},
}
for i,v in pairs(heroes[name]) do
print(i)
end
The reason that the code does not work is that name is not defined in the code you provided. Without the definition of name , heroes[name] would not refer to any key in the heroes table, and the for loop would not iterate over any values
You need to define the name variable before using it in the loop. For example, if you want to iterate over the keys and values of the “Archer” entry in the heroes table, you can modify the code as follows
local heroes = {
["Archer"] = {Damage = 2},
["Fire Wizard"] = {Damage = 5},
["Builder"] = {Heal = 25},
["Gunner"] = {Damage = 1},
}
local name = "Archer" -- define the name variable
for i,v in pairs(heroes[name]) do
print(i, v) --> Damage 2
end