Nim macro parameters

here is the code i want to compile:

macro defineSomething(amount:expr):stmt=
   var amountInt = intVal(amount).int
   # Boring staff

defineSomething(42);

      

It works great. I have everything I want in my macro, I can manage staff in my own way.

But then I think it would be better to remove the magic number in some constant settings:

const MAGIC_AMOUNT:int = 42

# Whole lot of strings
defineSomething(MAGIC_AMOUNT)

      

This code doesn't work. Because it is MAGIC_AMOUNT

literally not an integer value as opposed to a magic number 42

.

So how do I get the value of my variable inside macros in nim?

+3


source to share


2 answers


Untyped expressions . Since you really want to get integers, you can specify the typed parameter and then this should compile:

import macros

macro defineSomething(amount: typed):stmt=
  echo getType(amount)
  var amountInt = intVal(amount).int
  echo "Hey ", amount_int

const MAGIC_AMOUNT = 42
defineSomething(43)
defineSomething(MAGIC_AMOUNT)

      



Or just use normal int

as the type of the parameter if you don't want to pass other types also case

by the kind parameter inside your macro.

+2


source


By default, macros will receive AST expressions rather than values. If your macro needs to work with specific values, you need to use static parameters:

macro defineSomething(amount: static[int]): stmt=
  echo "int value: ", amount + 100

const MAGIC_AMOUNT = 42

defineSomething(43)
defineSomething(MAGIC_AMOUNT)

      



This will print at compile time:

int value: 143
int value: 142

      

+3


source







All Articles