How can I get a key's name inside a table?

Hey! I’m trying to get a key’s name and use it in another table. :grinning:

Code Example:

local ExampleTable = {
Run = Enum.KeyCode.W
}

In this example, I would want to get the “Run” variable, and use it as a string. Hopefully this is understandable enough, and responses would be greatly appreciated! :grinning:

You could use a for loop here where key is the and value corresponds to the value the key holds

for key, value in pairs(ExampleTable) do

end
5 Likes
local ExampleTable = {
Run = Enum.KeyCode.W
}

local find = table.find(ExampleTable, Run)
print(find)

table.find doesn’t work for key-value pairs. It’s designed for index-value pairs.
Also the author of this post wants to get the key part of the key-value pair and using table.find would return the value part.

1 Like

Then try:

 local ExampleTable = {
 Run = Enum.KeyCode.W
 }
 
 for i,v in pairs(ExampleTable) do
  print(v)
 end

Expected output:

image

OR

local ExampleTable = { Run = Enum.KeyCode.W }
     for i,v in pairs(ExampleTable) do
      print(i)
     end

Expected output:

image

1 Like

Pretty sure author wants to get the key part so it has to be print(i) instead which is almost no different than the first reply to this post.

Oh i thought he wanted the W key
anyways i edited it and put both xd

local variable = ExampleTable.Run
if game:GetService("UserInputService"):IsKeyDown(variable) 
then print(variable) 
end

I don’t think he wanted this?

he can use for i so it execute keys at the same time
with less code.

This is a more direct way

ExampleTable[“Run”]

there is an indirect way, in case you don’t know the name of the key in advance, and that is to forward the name from the local script,

this is oversimplified for the sake of example

Event.OnServerEvent:Connect(function(player, key)

ExampleTable[key]

end)

He wants to get the name of the key from a value in the table, not the other way around.

In that case his approach is completely wrong

if you want to get the key that was pressed and turn it into a string all you need is something like this

local KeyString = nil

UserInputService.InputBegan:Connect(function(key, IsTyping)

if IsTyping then return end --make sure the player isnt using chat

if key.KeyCode == Enum.KeyCode.W then

print (Key.KeyCode.Name)

KeyString = Key.KeyCode.Name

end)

Key.KeyCode.Name returns a string value of the key pressed so pressing W would return “W”

The second example of using the index with a in pairs loop worked perfectly for me, thanks!

1 Like