I tried to write my own metatable script but I end up with an error and I have no idea how to fix it.
local CSSComponent = {}
CSSComponent.__index = CSSComponent
CSSComponent.ClassName = "CSSComponent"
local ReplicatedStorage = game:GetService("ReplicatedStorage")
local CollectionService = game:GetService("CollectionService")
local Packages = ReplicatedStorage.Packages
local Signal = require(Packages.Signal)
function CSSComponent.new()
local Tags = {}
setmetatable(Tags, CSSComponent)
Tags = {
["UsingMove"] = {};
["Stunned"] = {};
["Ragdoll"] = {};
["Immunity"] = {};
};
return Tags
end
function CSSComponent:AddTag(List, Tag)
if not self.Tags[Tag] then return end
local relatedTag = self.Tags[Tag]
for _, obj in pairs(List) do
CollectionService:AddTag(obj, Tag)
table.insert(relatedTag, obj)
end
end
function CSSComponent:RemoveTag(List, Tag)
if not self.Tags[Tag] then return end
local relatedTag = self.Tags[Tag]
for _, obj in pairs(List) do
if CollectionService:HasTag(obj, Tag) then
CollectionService:RemoveTag(obj, Tag)
for number, instance in pairs(relatedTag) do
if instance.Name == obj.Name then
table.remove(relatedTag, number)
end
end
end
end
end
return CSSComponent
@drlandru is right, the methods should be called on the constructed object, which will be passed as self when the function is called with a colon.
However, there are also some other small mistakes.
In the constructor, you are declaring Tags, respectively self in the called methods. After setting the metatable, you are setting Tags to the table, losing the metatable in the process.
The passed self is Tags, therefore Tags.Tags is nil, and Tags.Tags[nil] causes an error.
Update.
I haven’t had a chance to test the code, but this is it.
Code
local CSSComponent = {}
CSSComponent.__index = CSSComponent
CSSComponent.ClassName = "CSSComponent"
local ReplicatedStorage = game:GetService("ReplicatedStorage")
local CollectionService = game:GetService("CollectionService")
local Packages = ReplicatedStorage.Packages
local Signal = require(Packages.Signal)
function CSSComponent.new()
local Tags = {
["UsingMove"] = {};
["Stunned"] = {};
["Ragdoll"] = {};
["Immunity"] = {};
}
setmetatable(Tags, CSSComponent)
return Tags
end
function CSSComponent:AddTag(List, Tag)
if not self[Tag] then return end
for _, obj in List do
CollectionService:AddTag(obj, Tag)
table.insert(self[Tag], obj)
end
end
function CSSComponent:RemoveTag(List, Tag)
if not self[Tag] then return end
for _, obj in List do
if CollectionService:HasTag(obj, Tag) then
CollectionService:RemoveTag(obj, Tag)
table.remove(self[Tag], table.find(self[Tag], obj))
end
end
end
return CSSComponent