Converting a string to an Enum

I want to convert a string to enum

“Enum.KeyCode.X” (string)
to
Enum.KeyCode.X

Simply use the built-in tostring() function to achieve that.
Example:

local str = tostring(Enum.KeyCode.X);
print(typeof(str)); --string

Misread :man_facepalming:
You can use some string manipulation to attain that:

local code = str:reverse():split(".")[1]:reverse();
return Enum.KeyCode[code];
5 Likes

This is way easier if you just use string patterns

Enum.KeyCode[str:match('[^.]*$')]
2 Likes

"Enum.KeyCode"..Enum.KeyCode.X.Name

Never mind, this is for string to enum not enum to string.