3 ms·
Oh, so it's like Rust's `macro_rules!` identifier rule? Rust's `macro_rules!` macros operate on ASTs, so the `x` inside a macro definition is different to the
by wizzwizz4 5y ago
Oh, so it's like Rust's `macro_rules!` identifier rule?
Rust's `macro_rules!` macros operate on ASTs, so the `x` inside a macro definition is different to the `x` in the scope where the macro is used, even though the textual representation of the identifier the macro inserts into the place it's used might be identical. This means that:
macro_rules! add_two {
($i: ident) => {
let x = 2;
$i += x;
}
}
fn main() {
let mut x = 5;
add_two!(x);
println!("{}", x);
}
appears to become:
fn main() {
let mut x = 5;
let x = 2;
x += x;
println!("{}", x);
}
but it still prints 7, not 4, because they're two different `x`s. (Of course, Red has first-class metaprogramming, so it's a lot better.)
- greggirwin 5y agoSomething like that, yes. Red has macros as well, with a key difference being that at compile time, for all macros, there is no runtime context to bind to. Sometimes this helps, sometimes it's a limitation. For example, interpolation at runtime can be tricky, but isn't as flexible if done with macros.