recently have been going through some of the older code in my current project, and I’ve been improving things, such as the way I’m making sure an Instance
has a specific property
I originally was using a very inefficient method
local function HasProperty(Obj : Instance, Prop : string) : boolean?
local Clone = Obj:Clone()
Clone:ClearAllChildren()
return (pcall(function()
local Property = Clone[Prop]
Clone:Destroy()
return Property
end))
end
however, cloning clearly wasn’t going to be good in the long run, so I swapped over to my current solution, which checks for an object with the class as a child, if it finds one it checks if it has a property, and if not, it creates a new one using Obj.ClassName
and checks it, parenting it to where I check for the objects originally(caching it so it doesn’t need to create and destroy it endlessly)
local function hasProperty(Obj: Instance, Prop: string): boolean
return pcall(function()
local Class = script:FindFirstChildWhichIsA(Obj.ClassName) or Instance.new(Obj.ClassName, script)
return Class[Prop]
end)
end
would it be better for me to not cache an object for each ClassName
when it gets called(meaning calling :Destroy()
before returning the result), or is there a method that would work without needlessly adding new instances?
(no I can’t just use Obj[Prop]
since it could return children, hence why the first solution I used had :ClearAllChildren()
, and checking typeof(Obj[Prop]) ~= "instance"
would falsify properties with a object value)