How do you go about checking if multiple children of a path exist

Im not sure how to give this a proper title but the explanation will make sense

So normally, if you wanted to check if an instance exists youd go like

if game.Workspace.Sounds.SFX.Something then --or use :FindFirstChild() 
    --do stuff
end

The problem is, by doing this, if Sounds doesnt exist, or SFX doesnt exist, it also errors
Is there a way to check if all the instances in a path exist so that i dont have to go like

if game:FindFirstChild("Workspace") then
    if game.Workspace.FindFirstChild("Sounds") then
        if game.Workspace.SoundsFindFirstChild("SFX") then
--etc

Or do i have to create a custom function myself that does that

3 Likes

There is no universally good solution for this, but in your scenario It would benefit you to use guard closures.

local soundsFolder = workspace:FindFirstChild("Sound")

--// This is guard closure
if not soundsFolder then
    return
end

local sfxSound = soundsFolder:FindFirstChild("SFX")

if sfxSound then
    --// Do stuff
end

There is also a way which is not exactly the best, but whenever there is really long path which you cannot define beforehands pcall can be used

local success, soundInSounds = pcall(function()
    return workspace.Sounds.SFX.Attack.Punch1
end)

--// Guard closure, doesn't exist
if not success then
    return
end
local function GetPathEnd(path: string): Instance?
    local elements = path:Split(".")
    local currentEnd: Instance = game
    
    while currentEnd:FindFirstChild(elements[1]) do
        currentEnd = currentEnd:FindFirstChild(elements[1])
        if not currentEnd then
            return
        end
        table.remove(elements, 1)
    end
    return currentEnd
end

--demonstration for your example
local path = "Workspace.Sounds.SFX"
local endObj = GetPathEnd(path)
if endObj then
    --do stuff
end

This probably isnt the best way to write something like this, and I wouldnt recommend something like this in the first place. One method that seems plausible is using an ObjectValue parented to somewhere close to the script and storing the end item’s location there. I’m sure theres also a really good way to do this with a module script.
It’s always good to experiment with different approaches to the same problem. You may find a way better way to solve something.

Edit:
The person above me also has a good point. pcalls are really powerful. I dont really like them for stuff like this, but I also use strict type checking, so an approach like mine works better there anyway. Neither of our solutions are perfect; the best one is going to be way simpler.

if you want to find a specific children within multiple instances/parents use :FindFirstChild(NAME,true)
notice how the FindFirstChild has a true parameter that means it will check all of the parent’s children until it finds that name

From the documentation if you can’t find it somehow
`If the optional recursive argument is true, this function searches all descendants rather than only the immediate children of the Instance

2 Likes

It all entirely depend on your game structure. Here is an example based on the example you gave.

local function getSFX(args)
--all code here
return SFX
end
-- You can use logic statements in your vars, here is an example
local workspace = game:GetService("Workspace") -- this will never return nil, 
--because all services exsits and roblox makes sure to give you one.
local SoundsFolder = workspace:FindFirstChild("Sounds") or Instance.new("Folder", workspace) -- Parent it directly if you dont want the name to be changed

-- this over here make sure that if it doesn't find sounds, it auto create a folder.
local SFX = SoundsFolder:FindFirstChild("SFX") or getSFX(args)-- you can clone SFX from another folder
-- if you have it that is.

this example not only checks, but creates if it doesn’t exists too. You can even use a function that returns the instance.

if game.Workspace.Sounds.SFX:FindFirstChild("Something") then
	--do stuff
end
local sfx=game.Workspace:WaitForChild("Sounds"):WaitForChild("SFX")
--
if sfx:FindFirstChild("Something") then
	--do stuff
end

Sorry, messed that up at first.

you can use and-or statements for this.

local sounds = workspace:FindFirstChild("Sounds")
local sfx = sounds and sounds:FindFirstChild("SFX")

if (not sfx) then
    --sfx not found!!
end

but, if your script relies on these and you know there’s no circumstances where they should not exist, use WaitForChild.


a little confused what you mean by this. if the instance doesnt exist and you use direct indexing, it will throw the x is not a valid member of y error. if you use FindFirstChild, it’ll return nil if it does not exist. nil is a falsy value in Luau, meaning if it’s rawly checked in if statements it’ll be treated like false, and instance userdatas are truthy, as are all userdatas, so I don’t see the need for a ~= nil check here. Could you explain?

Try this script by itself. Test it with something and without something…
It will not error either way…

task.wait(3)
local sfx=game.Workspace:WaitForChild("Sounds"):WaitForChild("SFX")
--
if sfx:FindFirstChild("Something") ~=nil then
	sfx.Something:Play()
else
	print("Something is missing")
end

It’s a way to refer to something and test its existence without throwing an error if it doesn’t exist at all.

yes, but that’s not my point. my point is that the ~= nil check is not necessary due to how Luau evaluates if statements, hence I was confused about your original reply, which is what I’m asking about.

In fact, I removed the ~= nil check and it still worked fine. Also, adding a task.wait at the top and then using FindFirstChild isn’t good practice for allowing instances to load - you should use WaitForChild if the instance or followed logic is necessary.

1 Like

This actually gives an error, not an error, rather a warning
If object doesnt exists, it will do infinite yield.
Like @12345koip said, logical operations would suffice.

1 Like

the taskwait was for this being a solo test ..

You’re right.. This is how you do this in other languages but the FindFirstChild is doing the nil check.
I fixed the post.

@ LamSouls odd I ran the script 6 times without an error.

2 Likes

unless other languages with userdatas (potentially under a different name) treat their version as falsy, this should persist across languages.

Nonetheless, I appreciate the fix.

1 Like

Ya my bad totally … that’s what you get when assembler is your language of choice most your life.

2 Likes

This works because we assume the folder of sfx wasnt deleted or moved.
However at the same time you can tun this without waitforchild and it would work, in fact it would be more optimized.And also we dont want randomness in our scripts.

Using logical operations, not only would it help our script move, it would make our script more organized.

However i dont want to keep yapping, this is actually another way.

Appreciate the fix too

Oh I get it WaitForChild is the lock on call and FindFirstChild is what I’m calling a nil check call.
Clearly I’ve been double checking that in the same call thinking Roblox didn’t have the solo command for this. It turns out I was using that command at the time … :rofl:

1 Like

Kind of jumping in the middle of all this,

But cant you just use a tag with collection service?

Wouldnt that simplify everything if there is a certain item needed?

So if you are adding sound.sfx mid game through another script could use

GetInstanceAddedSignal(tag : string)

Or if it is already set up, use

GetTagged(tag : string)

1 Like

It could work, however colllection is meant for multiple groups.
Yeah, you can use getalltags. But that would mean you would need to do an loop which wouldnt be optimized.

I meam cant you just do

CollectionService:GetTagged(tagName)[1]

Which will return the first item that is tagged that?

Re-reading this I’m not sure how all that got derailed so badly…
The answer would be yes, you have to do it yourself.

This would add additional complexity which yes, is not alot but you would still need to find said instances one way or another.

It would work great for most scenarios as in having specific sound with specific index, but I think developer is implying that it might or might not exist and if that would be the case you would need to develop some handler which automatically sets tags.

I personally prefell my pcall solution as it is simply one function call with maintaining readability and simplicity.

1 Like