Many scripters who have used Python or C# and are beginners in Lua may wonder now, just like I did when I started it, how do you create custom Enums in Lua?
Now, while there isn’t a way to do it using core roblox fucntions or creating classes with Enums in the __index or defining the class as an enum as in Python, there are other ways of creating custom enums - by using dictionaries.
The way to do this is to create a ModuleScript, and inside of the module script define a global dictionary.
I’ll insert a
into ReplicatedStorage, and I’ll call it CustomEnum. You can call it anything you want, though.
Then, inside, you will see this(double click to open the script):
I, personally, always change the name ‘module’ to the same as the ModuleScript’s name, but I don’t think you have to. You can keep the name ‘module’, if you so wish.
Now, I have changed my script to this(again, the ‘module’ part can be whatever you wish):
Inside the script, write this:
Note: “CustomEnum” must be the same as the local variable at the top -
The part in blue, that comes after the name,
can be whatever you want - it is the name of your enum.
Then, on the left, in square brackets [] write the name of one of your enum’s values. Then, insert a space, an equal sign, another space and then write the value of the enum you have just named. Do this as many times as you want, once for each value you want your enum to store. It should end up something like this:
Again, you can have as many values as you want.
To access your enum from another script, type this:
The require() around the moduleScript’s path is needed to tell the script that you want to access the contents of the moduleScript. Of course, if the moduleScript is not in ReplicatedStorage, then you have to replace the contents of the parenthesis with the correct path.
And there you have it! Your own custom Enums - predefined variables stored inside a dictionary in a ModuleScript!
Please leave out criticism (except constructive one, I’m always looking out for ways to improve ), this is for beginners and it’s my first time making a tutorial.
Thanks!
If you want the code for the ModuleScript, here it is:
local CustomEnum = {}
CustomEnum.myCustomEnum = {
["On"] = true,
["Off"] = false,
["Blue"] = Color3.fromRGB(0, 255, 255)
}
return CustomEnum
P.S: If you liked this tutorial, please like it- it makes the roblox algorithm show it to users more often so beginners can find it more easily and find out how to create custom enums without having to go through the hassle of searching for it.