Double using macros:
var x = 10 double(x) echo x # Output: 20
Hint: Use
quote do:
.
quote do:
:
Builds an AST by shorthand, but lets you write Nim code as if it were regular code.
Use quote do:
to turn your code into the corresponding NimNode
structure.
Backticks (x
):
refer to the original identifier within the quoted block;
inject the original identifier (not a value) into the generated code.
Backticks work differently with templates/macros in Nim:
Templates don't use backticks. The parameter name (expr
) is used directly, as you're not working with the AST - you're doing direct code replacement/substitution.
Macros use backticks. With macros, you're working with ASTs. Thus parameters like expr
are not variables - they are NimNode
(s).
The resulting code (x = x * 2
) is generated and inserted at the macro call site.
Compare - this 'works', but it's not using the NimNode itself!
x = x * 2
Whereas if I write this:
template double(expr: untyped): untyped =
expr = expr * 2
echo m, " ", double(m), " ", m
See the resulting error, because of how/where the generated code appears (due to substitution): m = m *2
import macros
macro double(expr: untyped): untyped =
result = quote do:
`expr` = `expr` *2
var x = 10
double(x)
echo x # Output: 20