QueryDescendant: A selector-based variant of FindFirstChild/FindFirstDescendant

As a Roblox developer, it’s sometimes annoying to safely refer to instances deep in hierarchy without checking if every ancestor of the instance exists.

Currently

Finding an instance that may not exist

local vehicles = workspace:FindFirstChild("Vehicles")
if not vehicles then return end
local car1 = vehicles:FindFirstChild("Car1")
if not car1 then return end
local vehicleSeat = car1:FindFirstChild("VehicleSeat")

or

local vehicleSeat
pcall(function() vehicleSeat = workspace.Vehicles.Car1.VehicleSeat end)
--[[this would be much more inefficient because it can
    silently throw an error which takes dozens of microseconds]]

Waiting for an instance that may exist in the future with a time limit

local timeout = tick()+5
local vehicles = workspace:WaitForChild("Vehicles",timeout-tick())
if not vehicles or tick()>timeout then return end
local car1 = vehicles:WaitForChild("Car1",timeout-tick())
if not car1 or tick()>timeout then return end
local vehicleSeat = car1:WaitForChild("VehicleSeat",timeout-tick())

The problem is that it takes many lines to safely refer to an instance deep in hierarchy, especially when waiting for them.

With QueryDescendant

Accessing an instance that may not exist

local vehicleSeat = workspace:QueryDescendant(">#Vehicles>#Car1>VehicleSeat")

Waiting for an instance that may exist in the future with a time limit

local vehicleSeat = workspace:QueryDescendant(">#Vehicles>#Car1>VehicleSeat",5)
-- the parameter 5 here would be a time limit for waiting
-- none = no waiting
-- -1 = infinite wait

With QueryDescendant it would only be one line, and it wouldn’t throw an error if the instance doesn’t exist, instead it would just return nil.

If Roblox is able to address this issue, it would improve my development experience by making it easier to find or wait for instances deep in hierarchy.

As a fellow Roblox developer, I would greatly appreciate this feature if it is ever added.

https://create.roblox.com/docs/reference/engine/classes/Instance#QueryDescendants

QueryDescendants is for querying many instances, whereas QueryDescendant would be for querying only one, which would be more optimal because it doesn’t need to internally loop through every possible instance.

I wonder if it’d make more sense to make QueryDescendants return an iterator function, or some kind of state object which allows for specific queries similar to how the Enumerable type works in C#'s LINQ system.

I would NOT want this. Lua-C bridging is expensive, and you’re better off writing a wrapper if you really want an iterator function.


What order should this method search in? I’m sure the return order for QueryDescendants is currently undefined to leave room for more optimizations, but a method like this should be consistent like FindFirstChild.

Sorry if I’m mistaken, but wouldn’t you just use a module for methods like this?


For example, querying a descendant could look like this:

function queryFirstDescendant(start:Instance,...:string):Instance?
	local found = start
	for _,search in {...} do
		if found then
			found = found:FindFirstChild(search)
		else
			return nil
		end
	end
	return found
end

Usage Example:

print(queryFirstDescendant(workspace,'Baseplate','Texture'))

Then a descendant version of WaitForChild might look like this:

function waitForDescendant(start:Instance,...:string|number):Instance?
	local array = {...}
	local warning = os.clock()
	local hasWarned
	local timeout
	local lastValue = array[#array]
	if typeof(lastValue) == 'number' then
		timeout = warning + lastValue
	else
		warning += 5
		lastValue = nil
	end
	local found = start
	for _,search in array do
		if search == lastValue then
			break
		end
		local target = found:FindFirstChild(search)
		while not target do
			task.wait()
			target = found:FindFirstChild(search)
			if not target then
				if timeout then
					if os.clock() >= timeout then
						return nil
					end
				else
					if os.clock() >= warning and not hasWarned then
						hasWarned = true
						warn(`Infinite yield possible on '{found:GetFullName()}:WaitForChild("{search}")'`)
					end
				end
			end
		end
		found = target
	end
	return found
end

Example Usage 1:

print(waitForDescendant(workspace,'Baseplate','Texture'))

Example Usage 2:

print(waitForDescendant(workspace,'Baseplate','Texture',5))

If the final number is a number, it will be treated as the timeout time. Otherwise, it will give a warning after 5 seconds, but will continue to attempt to locate the descendant.


This isn’t to say that I’m against native solutions, though I will always attempt to create my own solution where possible. Many developers create entire module libraries for things like this.

The problem here is this is unnecessarily expensive.

Lua first has to make a new table, then find every descendant that finds the selector rule, then grow the table for each one. Keep in mind, it doesn’t know how large the table will be before hand.

If it does all that effort to create a table and fill it just for you to pop the first value, you’ve wasted all that energy for what?

This alternative would just need to give over one instance when it finds one, which skips all the table stuff.

I don’t quite understand. It would have to do a similar task behind the scenes regardless, would it not? The table length can also be pre-defined by how many inputs there are.

Even if you mean continuing to try a specific path, it’s still a dynamic method. It would certainly be faster if done natively, of course.

That could simply be return next(QueryDescendants(...)), returns the first descendant or nil

It does make for a much more suitable task on the ‘backend.’

Oh ok, I misunderstood. I agree that we need a built-in way to safely reference objects. Yes it’s easy to make a function to do so, but it’s something so basic that it should’ve been included a long long time ago. In the meantime though, as far as I’m aware QueryDescendants has a pretty minimal performance implication, you might try benchmark it yourself for your use case and see how it performs?

Yes, using a module for this would work, but it would be much slower and much less convenient than a built-in function. QueryDescendants in some cases is already almost as fast as manually refering to an instance deep in hierarchy, even though it can loop through many instances. This shows that it’s possible for Roblox to make a similar built-in function for querying only one instance and it could be even faster than chaining many FindFirstChild calls.

QueryDescendants is much faster than GetDescendants, in some cases almost as fast as manually refering to an instance. The reason why it’s not as fast as is because it’s looping through many instances which is more than what’s needed to just refer to one instance, and that’s why QueryDescendant would be more optimal for this purpose.

This is one of the things I dislike about QueryDescendants, like it helps reduce memory usage over calling GetDescendants but it’d be so nice to have an iterator so roblox doesnt have to allocate a whole bunch of new instance userdatas and a giant array if I wanted to iterate the entirety of the workspace.

bump this needs to be added and also WaitForQuery too

BUMP!! I DREAD FOR MORE SELECTOR BASED ENGINE LEVEL FUNCTIONS!
t

do not listen to this person, they are insane

they are planning on releasing something in collectionsservice that does this, you should see it released independently of server authority
tldr it acts as the tags stuff but with instance queries where you can assign callback functions to events

luagate :warning::warning::warning::warning::warning::warning::warning::warning::warning::warning::warning::warning::warning::warning::warning::warning::warning::warning::warning::warning::warning::warning::warning::warning::warning::warning::warning::warning::warning::warning::warning: