How to get name of "Index Key" from information in table?

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 :wink:!
(Note this was written on mobile)

2 Likes

I believe table.find is what you’re looking for.


https://developer.roblox.com/en-us/api-reference/lua-docs/table


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
6 Likes

I will give it a try thank you. (I will mark it as solution once I get it working) :smiley:!

I think it can be like this too:

local function getKeyFromId(keyId)
	for index, keyTable in pairs(myTable) do
		if keyTable.KeyId == keyId then
           return index
        end
	end
end
4 Likes

I agree, you should be returning index, not tablekeyid.

1 Like

The ide shows me an error near the +, to what is this? Anybody know?

@wc3u and @GAFFAL_1236 Thank you so much its working perfectly and I learn something new :smiley: :+1: !

1 Like

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.

Here’s the official github website for Luau

2 Likes