Adds an example of using ident to name procedures to the macros tutorial (#22973)

As discussed here: https://forum.nim-lang.org/t/10653

---------

Co-authored-by: ringabout <43030857+ringabout@users.noreply.github.com>
This commit is contained in:
CharlesEnding
2024-09-09 11:46:48 +02:00
committed by GitHub
parent 8b895afcb5
commit fcee829d85

View File

@@ -322,6 +322,36 @@ used to get this output.
raise newException(AssertionDefect, $a & " != " & $b)
```
Going further
-------------
It is possible to create more complex macros by combining different
`NimNode` symbols with `quote do:` expressions. For example, you may
use `newStmtList` to build your macro iteratively, and `ident` in cases
in which you wish to create an identifier from a string, as shown below.
```nim
import std/macros
macro createProcedures() =
result = newStmtList()
for i in 0..<10:
let name = ident("myProc" & $i)
let content = newLit("I am procedure number #" & $i)
result.add quote do:
proc `name`() =
echo `content`
createProcedures()
myProc7()
```
The call to `myProc7` will echo `I am procedure number #7`.
With Power Comes Responsibility
-------------------------------