Skip to content

Commit

Permalink
Allow returning a value from EntityMut::world_scope (bevyengine#7385)
Browse files Browse the repository at this point in the history
# Objective

The function `EntityMut::world_scope` is a safe abstraction that allows you to temporarily get mutable access to the underlying `World` of an `EntityMut`. This function is purely stateful, meaning it is not easily possible to return a value from it.

## Solution

Allow returning a computed value from the closure. This is similar to how `World::resource_scope` works.

---

## Changelog

- The function `EntityMut::world_scope` now allows returning a value from the immediately-computed closure.
  • Loading branch information
JoJoJet authored and ItsDoot committed Feb 1, 2023
1 parent ca5ab3d commit 425d7cf
Showing 1 changed file with 26 additions and 2 deletions.
28 changes: 26 additions & 2 deletions crates/bevy_ecs/src/world/entity_ref.rs
Original file line number Diff line number Diff line change
Expand Up @@ -540,9 +540,33 @@ impl<'w> EntityMut<'w> {
}

/// Gives mutable access to this `EntityMut`'s [`World`] in a temporary scope.
pub fn world_scope(&mut self, f: impl FnOnce(&mut World)) {
f(self.world);
/// This is a safe alternative to using [`Self::world_mut`].
///
/// # Examples
///
/// ```
/// # use bevy_ecs::prelude::*;
/// #[derive(Resource, Default, Clone, Copy)]
/// struct R(u32);
///
/// # let mut world = World::new();
/// # world.init_resource::<R>();
/// # let mut entity = world.spawn_empty();
/// // This closure gives us temporary access to the world.
/// let new_r = entity.world_scope(|world: &mut World| {
/// // Mutate the world while we have access to it.
/// let mut r = world.resource_mut::<R>();
/// r.0 += 1;
///
/// // Return a value from the world before giving it back to the `EntityMut`.
/// *r
/// });
/// # assert_eq!(new_r.0, 1);
/// ```
pub fn world_scope<U>(&mut self, f: impl FnOnce(&mut World) -> U) -> U {
let val = f(self.world);
self.update_location();
val
}

/// Updates the internal entity location to match the current location in the internal
Expand Down

0 comments on commit 425d7cf

Please sign in to comment.