3

Is there a possibility to get string representation of an expression (or an identifier) inside a template? For example, having the next code:

template `*`*(name: expr) {.immediate.} =
  var `name`* {.inject.}: string = ""
  # Want to print 'name' here, not its value like with backticks

Is it possible to get the string representation of the name expression inside a template?

Rostyslav Dzinko
  • 39,424
  • 5
  • 49
  • 62

1 Answers1

7

You can use the astToStr magic from the system module to do this:

template foo*(name: untyped) =
  var `name`* {.inject.}: string = ""
  # Want to print 'name' here, not its value like with backticks
  echo "the variable name is ", name.astToStr

foo test

The output will be:

the variable name is test

The use of the immediate pragma is discouraged with the latest version of the compiler. See the following answer for more details: typed vs untyped vs expr vs stmt in templates and macros

Community
  • 1
  • 1
zah
  • 5,314
  • 1
  • 34
  • 31