How do I get the index of a dictionary? I can’t come up with anything
local tbl = {
["A"] = 1,
["B"] = 4,
}
print(tbl["A"]) -- prints 1, how can I make it print A?
How do I get the index of a dictionary? I can’t come up with anything
local tbl = {
["A"] = 1,
["B"] = 4,
}
print(tbl["A"]) -- prints 1, how can I make it print A?
Few ways to do this. You could create a separate array called tblInverse
in which all of the keys are the same values, then set a metatable to tblInverse
to have new indices set when tbl
has new indices set.
Here is some example code without the metatable because that is just for some extra functionality.
local tbl = {
["A"] = 1,
["B"] = 4
}
local function createInverseTable(tbl)
local inverse = {}
for i, v in pairs(tbl) do
inverse[v] = i
end
return inverse
end
local tblInverse = createInverseTable(tbl)
print(tblInverse[4]) --// Outputs B
print(tblInverse[1]) --// Outputs A
Alternatively try implementing your own find
function using a linear search.
local function find(tbl, value)
for i, v in pairs(tbl) do
if (v == value) then
return i
end
end
end
local tbl = {
["A"] = 1,
["B"] = 4
}
print(find(tbl, 4)) --// Outputs A
print(find(tbl, 1)) --// Outputs B
What @EpicMetatableMoment said might work but I have an easier solution for you
You can try this:
local tbl = {
["A"] = 1,
["B"] = 4,
}
for i, v in pairs(tbl) do -- getting the for i, v in pairs loop to print A
print(i)
if i == "A" then -- if it's A then don't print anything else
break
end
end
This is easier to understand than what he said and should work perfectly.