for example if i had
local Table = {A = 10, B = 20}
how would i get the index if A or B
for example if i had
local Table = {A = 10, B = 20}
how would i get the index if A or B
Use the [index]
or .index
syntax.
FieldName =
is a sugar syntax for ["FieldName"] =
in table constructors.
uh sorry but i don’t quite understand
In this example, you would use either:
Table.A -- A
Table.B -- B
…or this…
Table["A"] -- A
Table["B"] -- B
You’ll mostly use the former case, but the latter case is used when it’s a variable or if the name contains whitespaces.
how does this get the index for a or b
I accidentally misread the question, or you might have written the question full of ambiguity or incorrect vocabulary(maybe). So if you want to get index from a value, you’ll have to iterate through it.
local testValue = 10
local function getIndexFromValue(value)
for index, indexValue in pairs(Table) do
if indexValue == value then
return index
end
end
end
print(getIndexFromValue(testValue))
Alternatively, there is a specific method for it too!
table.find(Table, 10) -- this doesn't work lol
table.find(Table, 20)
table.find
only accounts for integer indices so it returns a number
and not a string
so this doesn’t work.
I think I overlooked that detail, thank you very much. Clearly I’ve missed that it works on only “array-like” tables so that is scratched off the list.
Make reversed table via pairs if nil value is not there.
Since I don’t know what if ipairs works with non-integer…
figured it out on my own!!!