diff --git a/CHANGELOG.md b/CHANGELOG.md index 6bdff05..6d184cc 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,7 @@ ## Unreleased Changes +* Added `Instance:FindFirstChildOfClass()` ([#50](https://github.com/rojo-rbx/remodel/pull/50)) * Added support for CFrame ([#48](https://github.com/rojo-rbx/remodel/pull/48)) * Added support for Vector3, and improved Vector3int16 ([#46](https://github.com/rojo-rbx/remodel/pull/46)) * Added Color3.fromRGB(red, blue, green) ([#44](https://github.com/rojo-rbx/remodel/pull/44)) diff --git a/src/roblox_api/instance.rs b/src/roblox_api/instance.rs index 4ca7cf3..022e287 100644 --- a/src/roblox_api/instance.rs +++ b/src/roblox_api/instance.rs @@ -95,6 +95,29 @@ impl LuaInstance { Ok(child) } + fn find_first_child_of_class(&self, class_name: &str) -> rlua::Result> { + let tree = self.tree.lock().unwrap(); + + let instance = tree.get_by_ref(self.id).ok_or_else(|| { + rlua::Error::external("Cannot call FindFirstChildOfClass() on a destroyed instance") + })?; + + let child = instance + .children() + .iter() + .copied() + .find(|id| { + if let Some(child_instance) = tree.get_by_ref(*id) { + return child_instance.class == class_name; + } + + false + }) + .map(|id| LuaInstance::new(Arc::clone(&self.tree), id)); + + Ok(child) + } + fn get_descendants(&self) -> rlua::Result> { let tree = self.tree.lock().unwrap(); @@ -346,6 +369,10 @@ impl UserData for LuaInstance { this.find_first_child(&name) }); + methods.add_method("FindFirstChildOfClass", |_context, this, class: String| { + this.find_first_child_of_class(&class) + }); + methods.add_method("GetChildren", |_context, this, _args: ()| { this.get_children() }); diff --git a/test-scripts/find-first-child-of-class.lua b/test-scripts/find-first-child-of-class.lua new file mode 100644 index 0000000..4e5b6ed --- /dev/null +++ b/test-scripts/find-first-child-of-class.lua @@ -0,0 +1,14 @@ +local root = remodel.readModelFile("test-models/folder-and-value.rbxmx")[1] + +assert(root ~= nil) +assert(root.Name == "Root") + +local stringValue = root:FindFirstChildOfClass("StringValue") +assert(stringValue ~= nil) +assert(stringValue.Name == "String") +assert(stringValue.ClassName == "StringValue") + +local numberValue = root:FindFirstChildOfClass("NumberValue") +assert(numberValue ~= nil) +assert(numberValue.Name == "Number") +assert(numberValue.ClassName == "NumberValue")