Skip to content

Instantly share code, notes, and snippets.

@Sleitnick
Created August 31, 2023 13:28
Show Gist options
  • Save Sleitnick/8f029e98a000676e4826c80eb2055fec to your computer and use it in GitHub Desktop.
Save Sleitnick/8f029e98a000676e4826c80eb2055fec to your computer and use it in GitHub Desktop.
Find an instance within the Roblox game hierarchy starting at a given parent. Throws an error if not found. Optional IsA check.
--!strict
--[[
Find(parent: Instance, path: string, [assertIsA: string]): Instance
e.g.
child = Find(parent, "ChildName")
child = Find(parent, "ChildName", "BasePart")
child = Find(parent, "ChildName/Some/Nested/Object")
child = Find(parent, "ChildName/Some/Nested/Object", "BasePart")
--]]
local DELIM = "/"
local function fullNameToPath(instance: Instance): string
return instance:GetFullName():gsub("%.", DELIM)
end
local function Find(parent: Instance, path: string, assertIsA: string?): Instance
local instance = parent
local paths = path:split(DELIM)
for _, p in paths do
-- Error for empty path parts:
if p == "" then
error(`Invalid path: {path}`, 2)
end
instance = instance:FindFirstChild(p)
-- Error if instance is not found:
if instance == nil then
error(`Failed to find {path} in {fullNameToPath(parent)}`, 2)
end
end
-- Assert class type if argument is supplied:
if assertIsA then
if not instance:IsA(assertIsA) then
error(`Got class {instance.ClassName}; expected to be of type {assertIsA}`, 2)
end
end
return instance
end
return Find
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment