You canāt get a tableās ānameā because tables donāt have a name to begin with. Variable names does not equal to an objects name.
Only objects in Luau that actually have names are function that are declared with the function functionName()-end syntax where functionName is the name of the function. This name doesnāt change even after changing the variable that function is assigned to and setting the old functionName variable to nil.
You must make sure the table is a global variable inside your script (i.e donāt precede the declaration with ālocalā). Then, simply use getfenv() and you can find the tableās ānameā through there.
exampleTable = {
randomValue = "this is facts"
}
table.foreach(getfenv(),print) --> exampleTable {}
local tableName = nil
for i,v in pairs(getfenv()) do
if typeof(v) == "table" then
print(i) --> exampleTable
tableName = i
break
end
end
This is called the key NOT the name. If you want to get The key in a loop, it would look like this:
local tbl = {
["Hi"] = "Hello",
["Bye"] = "Goodbye",
}
for key, value in pairs(tbl) do
print(key, "has the value of:", value)
end
Knowing this, if you want to get the key by the value, you can make this function:
local tbl = {
["Hi"] = "Hello",
["Bye"] = "Goodbye",
}
function GetKeyByValue(Value, Table)
local Key
for key, value in pairs(Table) do
if value == Value then
Key = key
return Key
end
end
return Key
end
local Key = GetKeyByValue("Hello", tbl)
print(Key) -- This should print Hi
local tbl = {
["hi"] = {
["Test1"] = 1,
["Test2"] = 2
}
}
function CheckTableEquality(t1,t2)
for i,v in next, t1 do if t2[i]~=v then return false end end
for i,v in next, t2 do if t1[i]~=v then return false end end
return true
end
function GetKeyByValue(Value, Table)
local Key
for key, value in pairs(Table) do
if CheckTableEquality(value, Value) then
Key = key
return Key
end
end
return Key
end
local Key = GetKeyByValue({["Test1"] = 1, ["Test2"] = 2}, tbl)
print(Key) -- This should print hi
If you supply the value you are looking for as the first parameter and the table you are trying to find it in, it should return the key that stores that first value!
Credit to: @Aldanium for the CheckTableEquality function.