Detecting the type of EnumItem

Hello,

I’m writing a script which the user configures in a config script.
In one of the configuration fields, the user is asked to provide a font.

This is how it’s defined.

local font = Enum.Font.Gotham

In my main script, I’m trying to validate that the font variable is a Font. If the variable isn’t a font it sets it to a different font. However, when calling typeof on the value it just displays as EnumItem.

Is there a way I can detect what type of item the variable is?

E.G typeof(font) -> EnumItem.Font (the actual typeof returns EnumItem as described above).

typeof is used for determining what type of thing the variable is. So when you called it since “Enum.Font.Gotham” is a type of EnumItem, it printed that out.

whoops sorry, my mistake I was thinking properly for the printing part.

This wouldn’t work as you’re printing the value to the output stream.

(you can capture the output stream but it’s a hacky method)

You are able to do Enum.Font["the name of the font"], you can probably check if the font.Name exists in Enum.Font by simply doing.

if Enum.Font[font.Name] then

end

No idea if this would work

3 Likes

I’ve tried your idea. Unfortunately, it doesn’t work. When you perform tostring on the font variable it produces Enum.Font.blahblah not blahblah.

Yeah just did a quick fix, do .Name at the end instead maybe.

2 Likes

A possible solution would be to first convert the Enum to a string.

Then you could just manipulate the string to get the text between the periods, Font

And to convert this to the “Font” Enum, you could just do

thisEnum = Enum["Font"]

Of course “Font” would be replaced with the text between the periods, but this should work as a way to get the higher level Enum.

Here’s a code example I made:

local lowerLevelEnum = Enum.Font.Gotham

function GetHighestLevelEnum(lower)
	lower  = tostring(lower)
	local FirstPeriodIndex = string.find(lower,".",1,true)
	local SecondPeriodIndex = string.find(lower,".",FirstPeriodIndex+1,true)
	local UpperLevelEnum = string.sub(lower,FirstPeriodIndex+1,SecondPeriodIndex-1)
	return Enum[UpperLevelEnum]
end

local UpperLevelEnum = GetHighestLevelEnum(lowerLevelEnum) --> Enum.Font
3 Likes

Thank you @starmaq & @Vmena! I’ve managed to create a little function based of your ideas.

function isFont(obj)
	if typeof(obj) == "EnumItem" then
		return ({pcall(function()
			local x = Enum.Font[obj.Name]
		end)})[1]
	else
		return false
	end
end

If I run the following I get the following results:

isFont(Enum.Font.Antique) -> true
isFont(Enum.ActionType.Draw) -> false

6 Likes