Using loop variable as an input for a macro function


Hi, I have a simple question on macro function.

Let say I have a macro function

macro add_one(i::Int64)

which does the simple thing:

@add_one 1

gives 2 as expected. Then I want to use the function inside the for loop in the following way:

for i=1:100
  @add_one i 

then, I have an error:

MethodError: no method matching @add_one(::Symbol)
Closest candidates are:
  @add_one(::Int64) at Ind[94]:2

It seems like I cannot use i, the for-loop variable, as an argument of a macro function. Are there any ways to use i as an input for @add_one?


When you write a macro, the types it sees are the types of the code that’s provided to it. This is because macros are evaluated at compile time. The literal 1 is indeed just an Int64, but i is a Symbol. Try doing

macro add_one(i)


macro function

Macros are not functions.

:($(esc(i)) + 1)


This works!!! thanks for your comments. Thanks to ExpandingMan as well!