How do you detect what key the player is pressing?

So basically the issue is not how to run code via key press, I just want to find out what key they’re pressing.

I wrote a bit of sloppy code to get single keys:

if input.KeyCode ~= nil and input.KeyCode ~= Enum.KeyCode.Space and input.KeyCode ~= Enum.KeyCode.Backspace then
local Key = string.sub(tostring(input.KeyCode), string.len(tostring(input.KeyCode)), string.len(tostring(input.KeyCode))) end

This code takes Enum.KeyCode.S to a simple “S”
But if I were to hit Backspace for example it would change it to “e” since e is the last letter.

I want to print any key I press without using that sloppy string.sub() method
I’m completely clueless on how to accomplish this, Any help would be extremely helpful! :slight_smile:

2 Likes

You can get the keys being held down via UserInputService:GetKeysPressed.

This is used in Roblox’s own code (e.g. the freecam script)

3 Likes

Thank you for the suggestion, but this actually doesn’t help me achieve what I’m looking for, It still returns “Enum.KeyCode.S” and I’m just trying to get the string “S”

You could create a table that maps enums to a string

local keys ={
   [Enum.KeyCode.A] = "A"
   --etc
}
2 Likes

I’ll try this for sure, If it works as intended I will mark your suggestion as the solution. Be back in a few. :slight_smile:

If I am understanding correctly, you are trying to find the name of the key you are pressing.

You could try to use string.split() for this, and use “.” to split the text, to get only the name of the the key.

1 Like

Yes that is exactly what I am trying to do, I’m gonna read up on that real quick

Enums are UserData, not string. Here’s an example script you could use:

-- key = Enum.KeyCode.A

tostring(key):split(".")[3]
-- string:split(seperator) returns an ordered array of the elements
-- in our case, we'd get Enum, Keycode, A

EDIT: While this would work, @sircfenner’s solution is much more efficient and I’d strongly recommenced using it over this method!

2 Likes

EnumItems have a Name property that you can use for this.

5 Likes

All three of you gave me solutions, I find this one to be a lot more efficient, Thank you.

I wish I could mark more replies as solutions, Sadly I cannot so to @ElliottLMz and @mistrustfully thank you for your suggestion, I did not know string.split existed and I was going to ask around if something like this was possible, Thank you much!

3 Likes

Better yet, you could create a table that maps enums to actions or information so that you don’t need an if statement at all:

local keys = {
    [Enum.KeyCode.A] = function()
        doTheThing()
    end
}

or

local keyDirections = {
    [Enum.KeyCode.W] = Vector3.new(0, 0, -1),
    ...
}
5 Likes

Thanks for the suggestion! Definitely will try this to make my life easier in the future. :slight_smile:

1 Like