ch10.md 1.6 KB

Chapter 10. Macros

As we have seen templates can be used for tasks where ordinary procs fail. In some sense a template is more powerful than a proc. A macro is even more powerful than a template because a macro can inspect a body of code that is passed to it. The first macro can be very hard to understand because you don’t write the pattern that is expanded where the macro is invoked as you would for a template. Instead you write the instructions on how to create the pattern that is the code that is inserted where the macro is invoked. In other words the code is rather imperative and low level. The following example is a macro that turns the body of code that it receives into an empty list of statements (newStmtList()). This means that the body of code is ignored by the compiler: import std / macros 1 macro disable(body: untyped): untyped = 2

result = newStmtList() 3

disable: 4

drawText(10, 10, "Disabled piece of code!", Blue)

1 To work with macros an API is required, this API is in std/macros. 2 The macro declaration looks like the template declaration except that the

 keyword template was replaced by macro.

3 The result of the macro is a syntax tree that is an empty list of statements. 4 To invoke a macro, the same syntax is used as for procs and templates.

                                                                         43

Many more examples for macros can be found throughout the book but the better examples are too advanced for this introduction. And with this our first tour through Nim ends. Time to dive into the foxhole!