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

Add Instance:FindFirstChildOfClass() #50

Merged
merged 4 commits into from
May 10, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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")