|
| 1 | +use specs::prelude::*; |
| 2 | +struct Pos(f32); |
| 3 | + |
| 4 | +impl Component for Pos { |
| 5 | + type Storage = VecStorage<Self>; |
| 6 | +} |
| 7 | + |
| 8 | +fn main() { |
| 9 | + let mut world = World::new(); |
| 10 | + |
| 11 | + world.register::<Pos>(); |
| 12 | + |
| 13 | + let entity0 = world.create_entity().with(Pos(0.0)).build(); |
| 14 | + world.create_entity().with(Pos(1.6)).build(); |
| 15 | + world.create_entity().with(Pos(5.4)).build(); |
| 16 | + |
| 17 | + let mut pos = world.write_storage::<Pos>(); |
| 18 | + let entities = world.entities(); |
| 19 | + |
| 20 | + // Unlike `join` the type return from `lend_join` does not implement |
| 21 | + // `Iterator`. Instead, a `next` method is provided that only allows one |
| 22 | + // element to be accessed at once. |
| 23 | + let mut lending = (&mut pos).lend_join(); |
| 24 | + |
| 25 | + // We copy the value out here so the borrow of `lending` is released. |
| 26 | + let a = lending.next().unwrap().0; |
| 27 | + // Here we keep the reference from `lending.next()` alive, so `lending` |
| 28 | + // remains exclusively borrowed for the lifetime of `b`. |
| 29 | + let b = lending.next().unwrap(); |
| 30 | + // This right fails to compile since `b` is used below: |
| 31 | + // let d = lending.next().unwrap(); |
| 32 | + b.0 = a; |
| 33 | + |
| 34 | + // Items can be iterated with `while let` loop: |
| 35 | + let mut lending = (&mut pos).lend_join(); |
| 36 | + while let Some(pos) = lending.next() { |
| 37 | + pos.0 *= 1.5; |
| 38 | + } |
| 39 | + |
| 40 | + // A `for_each` method is also available: |
| 41 | + (&mut pos).lend_join().for_each(|pos| { |
| 42 | + pos.0 += 1.0; |
| 43 | + }); |
| 44 | + |
| 45 | + // Finally, there is one bonus feature which `.join()` can't soundly provide. |
| 46 | + let mut lending = (&mut pos).lend_join(); |
| 47 | + // That is, there is a method to get the joined result for a particular |
| 48 | + // entity: |
| 49 | + if let Some(pos) = lending.get(entity0, &entities) { |
| 50 | + pos.0 += 5.0; |
| 51 | + } |
| 52 | +} |
0 commit comments