As you already said, it’s better to distinct instances by name.
I wouldn’t mind using your function. In fact, the exact logically same one can be found among my utilities, although I very rarely use it).
FindFirstChild() and related functions all perform a linear search with no guaranteed order. Your inference about internal implementation sounds right, and a custom function is just a tad slower version.
I wouldn’t strees over execution time too much, unless the search is done on a large pool of instances. Usually, it ought to be clear where approximately the instance should be, to reduce the queried collection. In concrete examples, workspace:FindFirstChild("Name", true)
looks terribly wrong.
Regarding a combination of `FindFirstChild()` and `FindFirstChildOfClass()` or `FindFirstChildWhichIsA()`
Relying on this combined search is not safe! The result is not what one would expect at a quick glance. It’s based on how ternary operators work!
The decal in your test is inside an instance, and the second search (FindFirstChildOfClass
) is not recursive, so the result is Part and nil
, which makes it nil
.
Why is this not safe?
Look at the following two demonstrations.
local instance1, instance2 = Instance.new("IntValue"), Instance.new("Part")
local i = instance1 and instance2
print(i) --> Part
Why? Because instance1
serves as a truthy condition.
local path = folder:FindFirstChild("Part") and folder:FindFirstChildOfClass("ModuleScript")
local module = require(path) -- all good :)
In this case, if FindFirstChild()
doesn’t return anything, the path is not even an instance reference but a falsy boolean.
local path = false and folder:FindFirstChildOfClass("ModuleScript")
print(path, typeof(path)) --> false, boolean
Which is, in Luau specific ternary operators, identical to:
local path = if false then folder:FindFirstChildOfClass("ModuleScript") else false
If you really have to find an instance with a name and a class, just use a custom function like yours.
Updates.
The changes are an additional example and some rephrased sentences for clarity.