var x = 10 double(x) echo x # Output: 20
quote do:
builds an AST, but lets you write Nim code as if it were regular code.
quote do:
builds an AST, 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 that generated code.
Backticks work differently with templates/macros in Nim:
Templates don't use backticks. The parameter name (expr) is used directly, because you're not working with the AST - you're doing code substitution.
Macros use backticks. With macros, you're working with ASTs. Also, parameters like expr are not variables - they are NimNodes.
The resulting code (x = x * 2
) is generated and inserted at the macro call site.
This 'works', but it's not using the NimNode itself!
x = x * 2
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