What are Enumerations
Enumerations are a way to group constants that are numbers. A classic example of an enum are error codes. But considering this is Roblox, you’ve probably done something like this before
if userInput == Enum.KeyCode.C then
-- handle input
end
-- Because the KeyCode Enumeration is really a number,
-- the actual value is 99
print(Enum.KeyCode.C.Value == 99) -- true
Make Your Own Enum
There are many ways to implement enums depending on your project size and personal preference, but a general way to do it is like this.
-- making the enum
UserState = {Loading=0,Playing=1,Quitting=2}
-- using the enum
if User.UserState == UserState.Loading then
foo()
elseif User.UserState == UserState.Playing then
bar()
end
It’s like a boolean because its main purpose is for comparison, except it can have multiple values and a unique name.
Why not use another method
Alternatively in this situation you could use global number constants
local LOADING, PLAYING, QUITTING = 0, 1, 2
if User.UserState == LOADING then end
or you could also use strings
if User.UserState == "loading" then end
These are viable options and honestly it comes down to your preference. However, a problem with the string method is that you might have to type the same string multiple times. This has the potential to lead to an error and trying to find the 1 incorrect string out of 20, for example, would be difficult.
Alternative Luau Implementation
If you want to be more technical, you can also make and annotate the enum type in Luau.
--!strict
type enum = {
[string]=number
}
local MyEnum: enum = {Value=0}
Conclusion
Enums are a way group similar things together and potentially make your code more readable. It can also avoid having to compare the same or similar string literals multiple times.