Hello Devs,
I am wondering how can I get Key Name (“Key”, “KeyTwo”) from KeyId.
I will explain it in script that I made:
local mytable = {
["Key"] = {KeyId = 1},
["KeyTwo"] = {KeyId = 2},
}
local function getkeyfromid(myval)
for index, v in pairs(mytable) do
for index, tablekeyid in pairs(v) do
if tablekeyid = v["KeyId"] then
if tablekeyid == myval then
return v
end
end
end
end
end)
while wait(5) do
local myval = 1
print(getkeyfromid(myval))
myval = myval + 1
end
Problem is that the v is Table not the Key Name.
Thank you for your help !
(Note this was written on mobile)
Edit: Read your post a bit too fast, solution for your specific problem should be just to replace “return v” with “return index” (and also to rename the variables to something a bit more readable)
local myTable = {
["Key"] = {KeyId = 1},
["KeyTwo"] = {KeyId = 2},
}
local function getKeyFromId(keyId)
for key, keyTable in pairs(myTable) do -- iterate over myTable
for _, tableKeyId in pairs(keyTable) do -- look for the keyIds in myTable
if tableKeyId == keyId then -- check if the keyId is the keyId we're looking for
return key -- return the key
end
end
end
end
while true do
local myval = 1
print(getKeyFromId(myval))
myval += 1 -- changed to compound operator because it looks nicer
wait(5)
end
Compound operators (+=, -=, ..=, etc.) aren’t implemented in vanilla Lua, only in Roblox’s version of Lua, Luau. If you’re using an IDE which isn’t running on Luau (such as Repl), then it won’t recognise the compound operator and will raise an error.