I dont know how else to explain this in the title, so just hear me out:
Lets say you want to see if hello exists as one of the descendants of something.
Normally you would do this:
local obj = something.thing.another:FindFirstChild("hello")
To check if it exists, just do
if obj ~= nil then
Right? Well, wrong. If something or thing or another does not exist, that line will error.
So now our code becomes THIS THING: (or alternatively 4 if statements instead of using and)
if something and something:FindFirstChild("thing") and something.thing:FindFirstChild("another") and something.thing.another:FindFirstChild("hello") then
While this works, its super long and clunky, and just feels wrong.
What would be a way to simplify this without making a loooong if statement?
FindFirstChild can be called recursively to find a nested child. Try: local obj = something:FindFirstChild("hello", true)
which will attempt to find child “hello” anywhere in the children of “something”
Also: if obj ~= nil is the same logical statement as if obj since “if obj is not nonexistent” is the same as “if obj is existent”
Yeah I mean, it is pretty similar. So using pcalls could work for this situation. But from my understanding of the forum, I think it would be better to just use
if something and something:FindFirstChild("thing") and something.thing:FindFirstChild("another") and something.thing.another:FindFirstChild("hello") then
To make it shorter, just put something:FindFirstChild("thing") and something.thing:FindFirstChild("another") and something.thing.another:FindFirstChild("hello") in variables.
local found,obj = module.hasNested(something,"thing","another","hello")
if found then print("yippe") end
function module.hasNested(parent, ...:string) :(boolean,any)
local good, result = pcall(function(...)
for _, childName in pairs({...}) do
parent = parent[childName]
end
return parent
end, ...)
if type(parent)=="table" and good and result==nil then --tables don't error on nil members so we need to force a no
return false
else
return good, result
end
end
or if you don’t want to deal with that you can use
function module.waitForNested(waitTime :number?, parent :Instance, child :string, ... :string) :Instance?
if not (parent and child) then return parent end
return module.waitForNested(waitTime,parent:WaitForChild(child,waitTime),...)
end
A lot of great suggestions I’ve read. Personally, I’d just wrap it in a pcall because why not.
local success, errormessage = pcall(function()
if something.thing.another:FindFirstChild("hello") then
end
end)
if success then
else print(errormessage)
end
I know it’s not what pcalls are necessarily for, but who’s gonna stop me?