examples/queries/query_variables.rs
1use crate::z_ignore_test_common::*;
2
3use flecs_ecs::prelude::*;
4
5#[derive(Component)]
6pub struct Eats;
7
8#[derive(Component)]
9struct Healthy;
10
11fn main() {
12 let world = World::new();
13
14 let apples = world.entity_named("Apples").add::<Healthy>();
15 let salad = world.entity_named("Salad").add::<Healthy>();
16 let burgers = world.entity_named("Burgers");
17 let pizza = world.entity_named("Pizza");
18 let chocolate = world.entity_named("Chocolate");
19
20 world
21 .entity_named("Bob")
22 .add_first::<Eats>(apples)
23 .add_first::<Eats>(burgers)
24 .add_first::<Eats>(pizza);
25
26 world
27 .entity_named("Alice")
28 .add_first::<Eats>(salad)
29 .add_first::<Eats>(chocolate)
30 .add_first::<Eats>(apples);
31
32 // Here we're creating a rule that in the query DSL would look like this:
33 // Eats($This, $Food), Healthy($Food)
34 //
35 // example shows how the basics of how to use queries & variables.
36
37 let rule = world
38 .query::<()>()
39 // Identifiers that start with _ are query variables. Query variables
40 // are like wildcards, but enforce that the entity substituted by the
41 // wildcard is the same across terms.
42 //
43 // For example, in this query it is not guaranteed that the entity
44 // substituted by the * for Eats is the same as for Healthy:
45 // (Eats, *), Healthy(*)
46 //
47 // By replacing * with _Food, both terms are constrained to use the
48 // same entity.
49 .with_first_name::<&Eats>("$food")
50 .with::<&Healthy>()
51 .set_src_name("$food")
52 .build();
53
54 // Lookup the index of the variable. This will let us quickly lookup its
55 // value while we're iterating.
56 let food_var = rule.find_var("food");
57
58 // Iterate the rule
59 rule.each_iter(|it, index, ()| {
60 println!(
61 "{} eats {}",
62 it.entity(index).name(),
63 it.get_var(food_var.unwrap()).name()
64 );
65 });
66
67 // Output:
68 // Bob eats Apples
69 // Alice eats Apples
70 // Alice eats Salad
71}
72
73#[cfg(feature = "flecs_nightly_tests")]
74#[test]
75fn test() {
76 let output_capture = OutputCapture::capture().unwrap();
77 main();
78 output_capture.test("query_variables".to_string());
79}