Skip to content

Commit ebb57c5

Browse files
authored
bevy_reflect: Add FunctionRegistry::call (#15148)
# Objective There may be times where a function in the `FunctionRegistry` doesn't need to be fully retrieved. A user may just need to call it with a set of arguments. We should provide a shortcut for doing this. ## Solution Add the `FunctionRegistry::call` method to directly call a function in the registry with the given name and arguments. ## Testing You can test locally by running: ``` cargo test --package bevy_reflect --all-features ```
1 parent 5484d2d commit ebb57c5

File tree

1 file changed

+32
-1
lines changed

1 file changed

+32
-1
lines changed

crates/bevy_reflect/src/func/registry.rs

Lines changed: 32 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,9 @@ use std::sync::{Arc, PoisonError, RwLock, RwLockReadGuard, RwLockWriteGuard};
44

55
use bevy_utils::HashMap;
66

7-
use crate::func::{DynamicFunction, FunctionRegistrationError, IntoFunction};
7+
use crate::func::{
8+
ArgList, DynamicFunction, FunctionRegistrationError, FunctionResult, IntoFunction,
9+
};
810

911
/// A registry of [reflected functions].
1012
///
@@ -282,6 +284,18 @@ impl FunctionRegistry {
282284
}
283285
}
284286

287+
/// Calls the function with the given [name] and [args].
288+
///
289+
/// Returns `None` if no function with the given name is registered.
290+
/// Otherwise, returns the result of the function call.
291+
///
292+
/// [name]: DynamicFunction::name
293+
/// [args]: ArgList
294+
pub fn call<'a>(&self, name: &str, args: ArgList<'a>) -> Option<FunctionResult<'a>> {
295+
let func = self.get(name)?;
296+
Some(func.call(args))
297+
}
298+
285299
/// Get a reference to a registered function by [name].
286300
///
287301
/// [name]: DynamicFunction::name
@@ -463,6 +477,23 @@ mod tests {
463477
assert_eq!(value.try_downcast_ref::<i32>(), Some(&321));
464478
}
465479

480+
#[test]
481+
fn should_call_function_via_registry() {
482+
fn add(a: i32, b: i32) -> i32 {
483+
a + b
484+
}
485+
486+
let mut registry = FunctionRegistry::default();
487+
registry.register(add).unwrap();
488+
489+
let args = ArgList::new().push_owned(25_i32).push_owned(75_i32);
490+
let result = registry
491+
.call(std::any::type_name_of_val(&add), args)
492+
.unwrap();
493+
let value = result.unwrap().unwrap_owned();
494+
assert_eq!(value.try_downcast_ref::<i32>(), Some(&100));
495+
}
496+
466497
#[test]
467498
fn should_error_on_missing_name() {
468499
let foo = || -> i32 { 123 };

0 commit comments

Comments
 (0)