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!
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)
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.
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