Scripting Helpers is winding down operations and is now read-only. More info→
Ad
Log in to vote
1

How do I check if an instance has a certain property?

Asked by 9 years ago

Title says it all

To explain:

local property = "Name"; -- Name is a property every instance has.

for i,v in next, workspace:GetChildren() do
    if (v[property]) then
        print("found: "..tostring(v)..";\n    property: "..tostring(property));
    end
end

The above doesn't error because every instance in workspace has a property "Name"...

However:

Instance.new("StringValue", workspace);

local property = "Value"; -- Not every instance has this property 

for i,v in next, workspace:GetChildren() do
    if (v[property]) then
        print("found: "..tostring(v)..";\n    property: "..tostring(property));
    end
end

The above errors saying that "Value" is not a valid property of camera? Why does it error? I clearly state that IF the instance has a property of "Value", then to print. It completely ignores it.

0
Man, the way you're using lua...it looks like another language. This is totally beyond me. yoshiegg6 176 — 9y

1 answer

Log in to vote
0
Answered by
adark 5487 Badge of Merit Moderation Voter Community Moderator
9 years ago

I'm not certain why that would be erroring, but you can use pcall to catch any invalid accesses:

for i, v in next, workspace:GetChildren() do
    if pcall(function() v[property] end) then
        print("found: " .. tostring(v) .. ";\n  property: " .. tostring(property));
    end
end
0
I realised that, thanks anyway! Vlatkovski 320 — 9y
Ad

Answer this question