Scripting Helpers is winding down operations and is now read-only. More info→
Ad
Log in to vote
0

How to get the "key" from a KeyCode?

Asked by 4 years ago

So my question is this: How can I get the "key" from a KeyCode value?

Example of what I have:

game:GetService("UserInputService").InputBegan:Connect(function(input)
    workspace.Key.Value =tostring(input.KeyCode);
end);

print(workspace.Key.Value)

Currently if the key I press for example is "E" it will print "Enum.KeyCode.E". I want it to just print "E" instead.

I will also want to use this value to check for the button entered later with somthing like this:

local Key ="Enum.KeyCode."..workspace.Key.Value"

if(input.KeyCode ==Key)then
    print("Pressed key!")
end

(I assume the above code would work, haven't tested it.)

1 answer

Log in to vote
0
Answered by 4 years ago

If your purpouse is to simply capture the character that has been pressed in the keyboard and you make sure it's one character only you can simply invert the string in the value and get the first letter of the string, here is an example:

game:GetService("UserInputService").InputBegan:Connect(function(input)
    workspace.Key.Value =tostring(input.KeyCode);

    local invertKey = string.reverse(workspace.Key.Value);
    local Key = string.sub(invertKey, 1, 1);
end);

print(Key);

This will make sure that Enum.KeyCode.E will be written as E.edoCyek.munE and you will simply just "cut" the string by the first character and capture that in a variable.

In the case of having more than one character you can utilize string.split() and split the string by a definet character which in this case is the character . ( dot ) and then capture whatever character you want to capture in a variable.

Here is more information on string manipulation:

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

If you have any more questions feel free to ask! :)

0
instead of reversing the string you could use -1 as the beginning of the substring oreoollie 649 — 4y
0
That works greatly too, capturing the last character of the string. It would only work in case your keycode is only 1 character though! iDarkGames 483 — 4y
Ad

Answer this question