Automatically convert a number to it's Enum key counterpart

I hope this hasn’t already been answered, but I couldn’t find a thread about this on google. Any links towards those is appreciated!

Hello! I’m trying to create toolbar for my game, and I was wondering if there is a better, cleaner method of converting the numbers 1,2,3 etc. to their respective keyboard keys (i.e. 2 > Enum.KeyCode.Two).

I know that I could store these values in a table and search in it but I was hoping there is a better, preferably cleaner alternative of reaching the same result.

One way I’ve found to get the enums for the keys 1-9 is to simply add 48 to them. I don’t know how to cleanly link 0 to this, however.

https://developer.roblox.com/en-us/api-reference/enum/KeyCode

Not marking as a solution because I’m still fairly certain there is a better, universal way.

Enum.KeyCode[Number]

Should work

2 Likes

Actually, this is exactly what you should do—store each keycode in a table because enum values can change anytime and should not be directly indexed/played with. (for example, the number that you are using, 48, can change anytime.)

1 Like

Simplified version of the code:

for i = 1,3 do -- 3 = number of buttons
	cas:BindAction(tostring(i), handleToolbarSelection, false, Enum.KeyCode[i])
	-- Enum.KeyCode[tostring(i)] didn't work either.
end

Errors out as
1 is not a valid member of "Enum.KeyCode"

It is actually called one
Enum.Keycode[“One”]

1 Like

Then your reply didn’t answer anything, just generated another question: How do you go from “1” to “One”, from “2” to “Two” etc.