#EntityCommands: lifetime parameter instantiated with the lifetime `'w` as defined here

5 messages · Page 1 of 1 (latest)

dreamy osprey
#

I'm trying to implement a custom EntityCommand and I'm running into trouble with lifetimes. Can anyone help?

struct ReplaceIf<'w, C: Send> {
    entity: Entity,
    predicate: dyn Fn(&'w Option<C>) -> bool + Send
}

impl<'w, 's, C: Send> EntityCommand for ReplaceIf<'w, C>{ //Error: lifetime parameter instantiated with the lifetime `'w` as defined here
    fn apply(self, entity: Entity, world: &mut World ){
        if self.predicate(entity.get::<C>()) {
            println!("hello world!");
        }
    }
}


trait CommandsExt {
    fn replace_if<C: Send + Sync>(&mut self, entity: Entity, predicate: dyn Fn(Option<&C>)->bool + Send) -> &mut Self;
}

impl<'a> CommandsExt for EntityCommands<'a> {
    fn replace_if<C: Send + Sync>(&mut self, entity: Entity, predicate: dyn Fn(Option<&C>)->bool + Send) -> &mut Self {
        self.add(ReplaceIf{ entity, predicate, });
        self
    }
}

willow warren
#

Your lifetime 'w is tied to the ReplaceIf type, which must be 'static since it needs to fully own all of its data. You probably need to use HRTBs to communicate to the compiler that the lifetime is tied to the world

#

Something like:

struct ReplaceIf<C: Send> {
    entity: Entity,
    predicate: Box<dyn for<'w> Fn(&'w Option<C>) -> bool + Send>
}
#

(also note that you need to put trait objects behind something like a Box since they're unsized)

#

Although, I'm unsure the lifetime is even necessary. I think the compiler will automatically infer the correct lifetimes (could be wrong though)