Custom Enums: Learn something new everyday

Hello fellow developers!

I have noticed that a bunch of people use keys (from tables) in a weird way that has the potential of causing errors. I will provide many examples so it’s easier to understand.

Wrong:

local map = workspace.Map.Name
if map == "Campsite" then ... end

This approach might cause errors in the future if the map’s name changes, and it’s just looks like a child made it. So, let’s make it look more professionally:

-- Maps module script
local Maps = {}

-- Custom Enum
Maps.Enum = {
    ["Campsite"] = "Campsite" -- Placeholders
    ["Theme Park"] = "Theme Park"
}

-- Example function
function Maps.Load(map: string)
    local newMap = game:GetService("ReplicatedStorage").Maps[map]:Clone()
    newMap.Parent = workspace
end

return Maps

Now let’s use it from a script (preferably server script):

local Maps = require(pathwayToMapsModule)

local currentMap = Maps.Enum.Campfire
Maps.Load(currentMap)

Of course this is just an example and it won’t work properly if you use it more times than once (due to missing map cleanup function). This is just to help you guys learn something new.

This can also include everything you can imagine, not just strings.
Thanks! :fire:

2 Likes

Great tutorial.
#resources:community-tutorials

This would not work, as you cannot check the length of a dictionary.

1 Like

I am pretty sure it does work unless another script inserts a new element into the dictionary while the game is already running.

Probably a better example looks like this:

local MyEnum = {
	Foo = "Foo",
	Bar = "Bar",
	Baz = "Baz",
}

export type MyEnum = keyof<typeof(MyEnum)>

local function foo(bar: MyEnum)
	-- ...
end

-- Either is valid
foo(MyEnum.Baz)
foo("Baz")

-- Isn't allowed
foo("Invalid")

return table.freeze(MyEnum)
2 Likes

#Dictionary always returns 0.

local t = { key = "value", foo = 2, bar = setfenv }
print(#t) --> 0
1 Like

Oh yes you’re right. Apologies for the mistake :smile:

If you want to get the length of a dictionare you would need a function to count it, however that’s out the scope of this post, so I will just edit the original message.

Thank you for telling me :fire:

Yes that will indeed be better, but I didn’t want to complicate it with some “custom objects”. That maybe be confusing for some developers if they don’t know how it works, so I just kept it like that.

Though, I appreciate that, could help a lot of people :fire: