I'm trying to learn about macros, as meta programming is a concept I really loved when I found about it, and it can be really usefull in my current project.
I'm trying to make a macro to create entities with any number of components, something like :
let ecs = ECS::new();
let entity1 = create_entity!(ecs);
let entity2 = create_entity!(ecs, Position{x:1, y:2});
let entity3 = create_entity!(ecs, Position{x:3, y:-1}, Velocity{vx:0, vy:1});
There are several things I don't know how to do here :
- How can I have this fixed first parameter, and ensure it is a struct of type ECS ? the same way
println!()will allways have a string first ? I've looked the definition ofprintln!(), but couldn't look deeper into the functions that are called. - How can I pass a whole struct as a parameter, and interpret this correctly ?
As an example, here is a working function to create an entity with one component :
fn create_entity_1<C1, C2>(ecs: ECS, component1: C1, component2: C2) -> Entity {
let result_entity = ecs.create_entity();
ecs.components.add_comp_to_last(&result_entity, component1);
ecs.components.add_comp_to_last(&result_entity, component2);
return result_entity;
}
And obviously, with more component I "simply" need to add more of the second line.
This is what i've tried so far, but I'm struggling to understand what I'm doing :
// macros to create entities with any number of components
macro_rules! create_entity {
($ecs:expr; $($comp:literal),*) => {
let result_entity = $ecs.create_entity();
$ecs.components.add_comp_to_last(&result_entity, comp);
}
}
I've tried to read both The book and The little book of macros, But I'm lacking concrete example or explanations of the whole thing.