Custom Instance Method
I personally really like this. This is a way to allow you to give an instance your very own properties. For example, Iβd give a BasePart
the property: CreationDate
and it will return a table that acts just the same as a normal Basepart, but gives you an extra property called CreationDate
This is a very hacky way of doing it, but it may help in a few cases and is an interesting concept.
Source
local InstanceService = {}
function InstanceService.new(Class, Properties, CustomProperties)
-- Creates the Instance --
local NewInstance
if typeof(Class) == "string" then
NewInstance = Instance.new(Class)
elseif typeof(Class) == "Instance" then
NewInstance = Class
end
-- Sets the Properties --
for i,v in next, Properties do
if NewInstance[i] ~= nil and i ~= "Parent" then
NewInstance[i] = v
end
end
-- Sets Parent --
if Properties.Parent then
if typeof(Properties.Parent) == "Instance" then
NewInstance.Parent = Properties.Parent
elseif typeof(Properties.Parent) == "table" then
NewInstance.Parent = Properties.Parent.DefaultObject
end
end
local CustomFunctions = {DefaultObject = NewInstance}
-- [ Custom ] --
function CustomFunctions:SetProperty(Properties)
-- Sets the Properties --
for i,v in next, Properties do
if NewInstance[i] ~= nil and i ~= "Parent" then
NewInstance[i] = v
end
end
-- Sets Parent --
if Properties.Parent then
if typeof(Properties.Parent) == "Instance" then
NewInstance.Parent = Properties.Parent
elseif typeof(Properties.Parent) == "table" then
NewInstance.Parent = Properties.Parent.DefaultObject
end
end
end
for i,v in pairs(CustomProperties) do
CustomFunctions[i] = function(Self, ...)
if (Self ~= CustomFunctions) then
error("Expected ':' not '.' calling member function `Method'", 0)
return
else
return v(...)
end
end
end
return setmetatable(CustomFunctions, {
__index = function(self, Index)
if typeof(NewInstance[Index]) == "function" then
return function(self, ...)
return NewInstance[Index](NewInstance, ...)
end
else
return NewInstance[Index]
end
end,
__newindex = function(self, Index, Value)
NewInstance[Index] = Value
end
})
end
return InstanceService
How to use
Put the script into a module and require it. Like this:
local InstanceService = require(ModulePath)
Next, it is similar to Instance for intuitive purposes.
local InstanceService = require(ModulePath)
InstanceService.new(Class, Properties, CustomProperties)
The main difference is the second and third arguments, to demonstrate this, I will be creating a neon basepart parented to workspace. It will have a custom property named NewProperty
that is set to true
local InstanceService = require(ModulePath)
InstanceService.new("Part", {Name = "NewPart", Material = Enum.Material.Neon, Parent = workspace}, {NewProperty = true})
Congratulations, we now have an extra property to set, you can also make this extra property a function, or any datatype.
By the way, Iβm not the best explainer, so if you have any questions, you can ask me.