You can use tonumber("1")
and it'll return 1
, is there a similar function for enums?
I want to save some Enums in StringValues, so I'd need a function sorta like toEnum("Enum.KeyCode.LeftControl")
and have it return Enum.KeyCode.LeftControl
, instead of the string version.
I COULD just save "LeftControl
" in the StringValue and do "Enum.KeyCode[StringValue.Value]
", but I'd prefer to save the whole Enum thing in there to avoid any possible confusion, thanks in advance!
This is a hacky way and I would not recommend this. If you want to though then here's a solution.
function toEnum(s) local t = {} if not s:match("^Enum") then -- if not an enum then stop the function return end for match in s:gmatch("[^%.]+") do table.insert(t, match) --[[ split the string into different parts e.g {"Enum", "KeyCode", "LeftControl"} ]] end local function recurse(p, ...) --loop through table elements and index each recursively if getfenv()[p] then --grab the Enum global p = getfenv()[p] end if select('#', ...) > 1 then --if there is still something to be indexed return recurse(p[...], select('2', ...)) else return p[...] -- when it is done looping, return the final value end end local ret = recurse(unpack(t)) return ret end
Here's my solution, since the others' are hacky or otherwise unnecessarily complicated.
local function toEnum(str) local enum = Enum str = str:gsub("^Enum.", "") for part in str:gmatch("[^.]+") do enum = enum[part] end return enum end
Note that the "Enum."
prefix will be optional.
In its raw form an Enum is just a value but this will get very confussing for programmers if we do not assign meaning to what the value is.
An Enum is an object containing three pieces of information Name, Value and EnumType. More imformation can be found here.
In your case we can use the name if you build a key value pair with the Enum itself being the value.
Example:-
local keyNames = {} -- store the keyName = Enum for _, key in pairs(Enum.KeyCode:GetEnumItems()) do -- gets the list of enums for keys keyNames[key.Name] = key -- map key name to the enum end print(keyNames['LeftControl'])
Hope this helps.