Hey! I’m trying to get a key’s name and use it in another table.
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!
sjr04
(uep)
November 23, 2020, 11:18am
#2
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
Synitx
(Synitx)
November 23, 2020, 11:25am
#3
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
Synitx
(Synitx)
November 23, 2020, 11:32am
#5
Then try:
local ExampleTable = {
Run = Enum.KeyCode.W
}
for i,v in pairs(ExampleTable) do
print(v)
end
Expected output:
OR
local ExampleTable = {
Run = Enum.KeyCode.W
}
for i,v in pairs(ExampleTable) do
print(i)
end
Expected output:
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.
Synitx
(Synitx)
November 23, 2020, 11:39am
#7
Oh i thought he wanted the W key
anyways i edited it and put both xd
Wyzloc
(Wyzloc)
November 23, 2020, 11:41am
#8
local variable = ExampleTable.Run
if game:GetService("UserInputService"):IsKeyDown(variable)
then print(variable)
end
Synitx
(Synitx)
November 23, 2020, 11:43am
#9
I don’t think he wanted this?
he can use for i
so it execute keys at the same time
with less code.
Nogalo
(Nogalo)
November 23, 2020, 11:46am
#10
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.
Nogalo
(Nogalo)
November 23, 2020, 11:53am
#12
In that case his approach is completely wrong
Nogalo
(Nogalo)
November 23, 2020, 11:55am
#13
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