mirror of
https://github.com/nim-lang/Nim.git
synced 2026-04-06 07:38:24 +00:00
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:
30
doc/tut3.md
30
doc/tut3.md
@@ -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
|
||||
-------------------------------
|
||||
|
||||
|
||||
Reference in New Issue
Block a user