Macro transforming a function call to a new function definition and call the new function

Continuing the discussion from Make a variable as a global variable within a function:

Since the original conversation is too long, I separated this question.

Suppose the below codes:

function _my_func(a, b)
    c = 2*a
    b = b + 1
    a + b
end
function my_func(a)
    c = nothing
    b = a
    @log _my_func(a, b)
    @show c
end

Then, the definition of my_func should be

function my_func(a)
    b = a
    c = nothing
    # the content of `_my_func`
    function _my_func__LOG__(a, b)
        c = 2*a
        b = b + 1
        a+b
    end
    _my_func__LOG__(a, b)  # call the new function
    @show c  # make it 2*a
end

Is it possible? If so, what should I do?

Background of this question: I will define a dictionary __LOGGER_DICT__ (in my_func) and update it in _my_func.

In your function:

function _my_func(a, b)
    c = 2*a
    b = b + 1
    a + b
end

Both a and b are strictly local to the function, because they are given as arguments, so the reassignment to b in the second line will never affect any other b that is defined outside.

To give a counterexample, if this function is defined inside another local scope (e.g. inside a function), and c was also assigned in that outer local scope, the assignment of c in the first line would affect that other outer c (that’s the point of closures). This might be avoided by explicitly writing local c = 2*a.

So, in this particular example there is no need to rewrite the function with a macro, you could safely use _my_func inside my_func.

1 Like

You’re right. My example was wrong. It should be of variable c.
I’ll modify the original question.
No, I was confused.
The macro that I want to make is actually supposed to “change” the variable c!

BTW, do you think it’s possible to rewrite a function with a macro as I desire?