[nim-dev] How to generate {.gensym.} variable in a macro for a template?

  • From: mora <morapeter@xxxxxxxxx>
  • To: nim-dev@xxxxxxxxxxxxx
  • Date: Sat, 12 Sep 2015 11:05:31 +0000

Hi,

I would like to have a macro which generates a variable within a template:
```nim
template foo(): expr =
var id {.gensym.} = 10
id + 10

echo foo() # echos 20
echo foo() # echos 20

import macros
macro letsCreateVar(): stmt =
result = parseExpr("var id {.gensym.} = 10")
template foo2(): expr =
letsCreateVar()
id + 10

echo foo2() # echos 20
echo foo2() # error: redefination of 'id'
```
It might seem like this has no real usage, the actual example is complicated
(I'm happy to share if someone is interested). Is there a way to make this
compile?

Thank you,
Peter

Other related posts: