Handling of CollectionService:RemoveTag

I’ve always been skeptical about how my handling of CollectionService:RemoveTag() is, as you can call this function on Instances that do not have a tag without the error.

“RemoveTag will remove some tag from some object. This method will not throw an error if the object did not have the tag in the first place.” - RemoveTag’s API Reference.

I would gauge the need to use CollectionService:HasTag() before removing a tag based on the code itself but, I don’t exactly have access to said-inner workings.

My current assumption is that it works like this, instances are sorted in some cache (TABLE[TagName][Instance]) in which case, would make checking beforehand redundant.


Insightful comments are appreciated!

If the API says it wouldn’t throw an error if the instance didn’t have the tag why would it lie?

This is about if the intention of it not erroring is signalling to not check, not whether the API is “lying”.

I don’t understand how this makes a difference. Why would you need to check if a tag exists if you plan on removing it? Either way, the tag won’t exist under the instance and nothing would be changed than if it ran normally.

Out of curiosity, is there a real reason why you need to do all this work to begin with? What’s the Code Review to be done here, or what problem are you trying to solve? I don’t really understand what you’re trying to accomplish here other than figuring out how CollectionService works.

CollectionService tags appear to be handled a lot like dictionaries but are presented to developers in array formats for easier working with. You can test this out by attempting to add the same tag to an instance a few times and then check the instance’s tags, won’t appear five times. On a baseplate:

local CollectionService = game:GetService("CollectionService")

for i = 1, 5 do
    CollectionService:AddTag(workspace.Baseplate, "foobar")


It’s probably safe to assume that again, when the tags are serialised onto the instance they’re written in as a dictionary-like format but for developer-facing functions the tags are collected and put into an array then given back to the developer’s code for convenience’s sake - or for individual tags, it’s a lookup (e.g. HasTag). Assuming this logic is accurate, RemoveTag just sets a key in a dictionary to nil which is not invalid to do. Doing a lookup just to set a key to nil is pretty wasteful unless you have an explicit circumstance wherein you don’t want to overwrite something.

1 Like

The actual code review was moreless about my own usage of :HasTag() before :RemoveTag(), the rest was an attempt to (hopefully) strengthen my understanding of how the service handles those two functions.

It may have been easier to just ask around rather than posting about it, but I couldn’t personally find any answers that satisfied.

1 Like