I want to find the index instead of a value by using the value’s index (tables).
The issue is when I print a table, it will only return its value, but I want the value’s index. In this case, I want to check if myTable["Keys"] is named "Keys".
--simple explanation
local myTable = {}
myTable["Keys"] = {"123"}
print(myTable["Keys"]) -- returns {"123"} instead of "Keys", "Keys" is what I want.
-- usage case
local keyTable = myTable["Keys"]
-- tricky part, you can’t check if keyTable is named "Keys", instead you get {123} from print(keyTable).
--[[
--if there were some possible way to grab a table’s name
table.setname(keyTable, "Keys")
if table.getname(keyTable) == "Keys" then
for i, v in pairs(keyTable) do
--code
end
end
]
I have tried searching through the developer hub for table’s library, none of those functions can find the value’s index while utilizing the same index and value.
local myTable = {}
myTable["Keys"] = "123"
local function findKeyByValue(value)
for i, v in pairs(myTable) do
if v == value then
return i
end
end
return nil
end
print(findKeyByValue("123")) -- This?
What’s the use case for this? You could try adding some metadata to each array like this?:
local s = {
["Keys"] = {
Name = "Keys",
OtherInfo = 123,
Id = 1
},
["NotKeys"] = {
Name = "NotKeys",
OtherInfo = 456,
Id = 2
}
}
print(s["Keys"].Name) -- print's "Keys"
print(s["Keys"]) -- prints the table
You can’t do that with vanilla tables, you’ll need to use a for loop
for Key, Value in pairs(Table) do
print(Key .. ":" .. Value)
end
This also isn’t particularly useful to have, because you’d have to know what key you saved a value to anyways to actually save the value to a table.
EDIT 17/05/2024: I got a like notification on this post, and I want to point out 2 new features Luau has, String Interpolation and Generalized Iteration. You can now “interpolate” strings like so:
-- NOW:
local MyString = `{Name} = {Value}`
-- BEFORE:
local MyString = tostring(Name) .. " = " .. tostring(Value)
, and loops can be shortened to this:
-- NOW:
for Key, Value in Table do
end
-- BEFORE:
for Key, Value in pairs(Table) do
end
So, the original code can now be cleaned up to this:
for Key, Value in Table do
print(`{Key}: {Value}`)
end
Hashtables do NOT have an index. You can manually add a index, but if you really want to use numeric indices, you can just do so instead of string keys.
To get the index of a value in a table you can use a for loop like this:
local function getValueIndex(tbl, value)
for i, v in next, tbl do
if v == value then
return i
end
end
end
-----Usage-----
local tbl = {"Keys" = "123"}
local idx = getValueIndex(tbl, "123")
print(idx) -- Keys