Tutorial - Check if an object has property

Hello developers!
Sometimes we need to know if an object has a specific property, I discovered a way to do this and decided to share it with you!
(I know others discovered this trick way before me!)

I can’t really explain the code, but here is it:

function hasProperty(object, propertyName)
    local success, _ = pcall(function() 
        object[propertyName] = object[propertyName]
    end)
    return success
end

--<< Example: >>--

print(hasProperty(workspace.Part, "Text")) -- prints false
print(hasProperty(someThing.TextLabel, "Text")) -- prints true

Yep, that’s all.
I hope I showed something new, bye!

20 Likes

A less hacky alternative to doing this would be to use Anaminus’ api. It’s what Quenty uses for his Class Converter plugin.

https://anaminus.github.io/rbx/json/api/latest.json

3 Likes

I am kind of confused. How is this a tutorial if you don’t explain it at all? Kind of seems more like a community resource.

2 Likes

This code is so short I can’t explain anything about it.
I don’t feel like this is a community resource, this is like a little “code trick”.

3 Likes

A tutorial is explain it though, this is giving the code out for people who need it, it would be a community resource.

2 Likes

I have a question, would the following would be affected or not?
Let’s say I use this function in a for loop, and check with Decals and BaseParts. They both have Transparency, but it’s not the same when you select both part and decal in properties tab. What would happen?

1 Like

I think it would still work.
It’ll return true for both, because they have a property named “Transparency”.

1 Like

Ah yes, totally your code:

3 Likes

Now, I don’t knwo what are you talking about.
This code is NOT the same as mine. Even the variable names are different.
And I mentioned:

I won’t post a copy-paste version of somebody else.

Bro that’s a huge waste of the pcall function…

2 Likes

Now, I know I could do it with :FindFirstChild() too. But I figured out this first and it gets the job done.

There is a reason why :FindFirstChild() has word “child” in its name - :FindFirstChild() is for getting object’s children, it doesn’t work with properties.

Thanks for tutorial. It helped me a lot. :slight_smile:

If you are talking about :FindFirstChild() , then no, it doesnt work with properties.

3 Likes

Also i’d like to make a comment on this resource in general, you don’t really need this very much, an easier way would be to not loop through a varying table, identify members through a more conventional way, etc. Generally relying on pcalls for anything like this is pretty redundant.