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

How do I check if a property exists for a certain thing?

Asked by 5 years ago

So what exactly I'm trying to accomplish is I'm trying to make it so that if in a iv loop the v im looking for has a property named size but it keeps erroring at local script saying that local script does not have a size which I put a if not then to return end but it keeps doing the same thing erroring on LocalScript

Can anyone help ?

for i,v in pairs(game.StarterGui.ScreenGui:GetDescendants()) do
    if v.Size == true then
    print(v.Name..'has size')   
if not v.Size then
    return 
end     
end 

end

1 answer

Log in to vote
0
Answered by 5 years ago
Edited 5 years ago

You could use pcall(), which catches errors and prevents them from breaking your script. Calling a function with pcall() will return two or more values: the first one is a bool (true or false) which indicates if the called function ran without error, and the rest are any values returned by the called function.

Below, hasSizeProperty will be true if the inner function doesn't throw an error.

Furthermore, size will be set to v.Size.

for i, v in pairs(game.StarterGui.ScreenGui:GetDescendants()) do
  local hasSizeProperty, size = pcall(function()
    return (v.Size ~= v:FindFirstChild("Size")) and v.Size
  end)
  if hasSizeProperty then
    print(v.Name .. " has size " .. tostring(size))
  else
    -- do something when v does not have a property called "Size"
  end
end
1
Not reliable, think of the object's children! This is not restricted to properties User#24403 69 — 5y
0
True. I'll update my code to check for this case. WillieTehWierdo200 966 — 5y
Ad

Answer this question