Convert Char to Keycode

I am creating a game where individual keystrokes can be set to the player’s preference. The keystrokes are saved in a datastore as a string. They are then sent to the client to be used in-game.

How can I convert a String to a Enum.KeyCode to use with ContextActionService?

To convert from a KeyCode to a String is easy, but not the other way around:

local rightHandInput = Enum.KeyCode.One
rightHandKey.Frame.Key.Text = string.upper(string.char(rightHandInput.Value))

I tried looking on the wiki for a function to do this, but was out of luck in finding any.
I could create a custom table and then index it like so:

local keys = {[“A”] = Enum.KeyCode.A}

But this doesn’t seem very efficient for all the however many keys there are on the keyboard.

2 Likes

Enum.KeyCode[string.upper(string.char(rightHandInput.Value))] works fine

3 Likes

Straight to the point and concise.
Thank you.

Enums have a Name property.

print(Enum.KeyCode.One.Name) -- "One"

You can save that string and load as

local str = "One" -- your saved string
print(Enum.KeyCode[str]) -- Enum.KeyCode.One
13 Likes

This is probably a better solution than saving the character itself.

1 Like

One more question.
If the character inputs “1” into the TextBox, I could convert this to byte 49
But given these two things how can I get Enum.KeyCode.One

local str = "One" -- your saved string
print(Enum.KeyCode[str]) -- Enum.KeyCode.One

doesn’t work as I need the string name
and

Enum.KeyCode[string.upper("1")]

doesn’t work as It’s not a valid EnumItem (It has to be “One”)

Would I have to make the user press a ui button then the next key they press becomes binded? I have a feeling this would work much better.

Yea it’s probably better to make the next press key-binding rather than use a text-box.

1 Like