Hello, I am currently trying to study enumerations, but I am not quite understanding what the roblox dev website means. So I understand it takes a set of values, but what does it do with them? what type of values does it take? How do you know when you should use an enum or not? It would be much appreciated if you can explain it to me like I don't understand how it works, or any explanation at all really.
Enumeration
An “Enumeration”, or “Enum”, is a special data type that can take one of a set of values. What this means within ROBLOX, is there are set options that certain properties' values can be equal to, and these are enforced with the Enum
data type.
The reason you may have missed a lesson on Enums, is because they can be assigned with strings
as an overload. The reason you are confronting them now, is because to compare Enums you must write them out.
Material
One common example of an Enumeration is with the Material
property of a BasePart
.
Lets say you inserted a Part
into the workspace
, and wanted to see what it's Material
was.
print(workspace.Part.Material) --> Enum.Material.Plastic
Ahah! However, as I said previously, you can assign it either by it's Enum, or with a string as apart of an internal overload function
local part = workspace.Part part.Material = "Grass" print(part.Material == "Grass") --> false print(part.Material == Enum.Material.Grass) --> true part.Material = Enum.Material.DiamondPlate
KeyCode
Using your example, most people have to confront what an Enum
is when they start using UserInputService
, as there is a defined number of valid keys that can be pressed, so ROBLOX made an Enum for it.
local uis = game:GetService("UserInputService") uis.InputBegan:Connect(function(obj) print(obj.KeyCode) --> Enum.KeyCode.G if obj.KeyCode == Enum.KeyCode.G then print("You are a G!") --> You are a G! end end)
Conclusion
EnumItems are NOT strings, and when comparing them to anything you should take note their true value, otherwise you may find yourself stuck in a conditional statement.
They are useful for declaring a set number of options for a certain type of value.
Sources/Links - Enumeration - Enum Index
THIS IS NOT MY SOURCE NOR MY THING THIS WAS POSTED BY @amanda