More efficient method of checking for properties

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)

1 Like

A friend of mine has given me a much more elegant solution, that avoids using extra objects!
Figured I’d stick it here so if anyone else comes looking for a method they can get it

local function HasProperty(Obj: Instance, Prop: string): boolean
    return pcall(function()
        Obj:GetPropertyChangedSignal(Prop)
    end)
end

Thanks Tani! :smiley:

1 Like

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.