Skip to content
This repository has been archived by the owner on Jul 22, 2023. It is now read-only.

Commit

Permalink
Add Instance:FindFirstChildOfClass() (#50)
Browse files Browse the repository at this point in the history
* implement Instance:FindFirstChildOfClass()

* add entry to changelog

* fix error message

Co-authored-by: Lucien Greathouse <[email protected]>
  • Loading branch information
jeparlefrancais and LPGhatguy authored May 10, 2021
1 parent 51edda7 commit 92390de
Show file tree
Hide file tree
Showing 3 changed files with 42 additions and 0 deletions.
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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))
Expand Down
27 changes: 27 additions & 0 deletions src/roblox_api/instance.rs
Original file line number Diff line number Diff line change
Expand Up @@ -95,6 +95,29 @@ impl LuaInstance {
Ok(child)
}

fn find_first_child_of_class(&self, class_name: &str) -> rlua::Result<Option<LuaInstance>> {
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<Vec<LuaInstance>> {
let tree = self.tree.lock().unwrap();

Expand Down Expand Up @@ -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()
});
Expand Down
14 changes: 14 additions & 0 deletions test-scripts/find-first-child-of-class.lua
Original file line number Diff line number Diff line change
@@ -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")

0 comments on commit 92390de

Please sign in to comment.