0

Following this post, I defined a macro inside a function:

macro Name(arg)
    string(arg)
end

function myfunc(df)
    @Name df
end

tf = 3
myfunc(tf)

What I want is:

''tf''

But what I actually got is

''df''

Is there a way to achieve this?

Thanks

Likan Zhan
  • 1,056
  • 6
  • 14
  • 2
    You are passing the name `df` to the macro right here: `@Name df`, so then you will get "df". Furthermore, functions cannot know the names of the outside variables being passed to them, only their values. You'll have to somehow apply the the macro outside `myfunc`. – DNF May 24 '23 at 05:20
  • This is not possible, functions are not required to replace macros. Use the macro as a function-replacement`@Name(tf)` – Raumschifffan May 29 '23 at 14:42

1 Answers1

0

The function takes arguments by value (an integer here), so the name tf of the variable passed is not seen by the function body, only 3. Inside the function, df is what the macro sees, not the variable that supplied 3 to the function. You would have to put the macro call in as an argument:

macro Name(arg)
    string(arg)
end

function myfunc(df, name = @Name tf)
    println(df)
    println(name)
    println(@Name df)
end

tf = 3

myfunc(tf)
println()
myfunc(tf, @Name foo)

Result:

3       
tf
df

3
foo
df
Bill
  • 5,600
  • 15
  • 27