How to call arguments from outside of the scope

Hello is it possible to invoke a function to use variable from caller function scope using macros ? I think about sth like

function innerFunction()
println(a*4)
end

function outerContext()
a = 4
@useOutArgs innerFunction()
end

macro useOutArgs(ex)
return esc(:($ex))

end

outerContext()#return a not defined - I would like for it to print 16

Now Is it possible to modify useOutArgs macro to print 16 without passing a to arguments ?

No - only variables of the scope the function is defined in are accessible. You can’t use variables of a “sibling scope”. This is unrelated to macros, as they only transform some code into some other code. Scope is a semantic concept, while macros operate only on syntax.

What are you trying to achieve in the grand scheme of things? Is there a reason you can’t pass the variable into the called function directly?

3 Likes

You could define the inner function inside the outer function and then it would have access to the variables of the outer function.

5 Likes

I have quite nested function a lot of times i need to pass the variable from top function through all intermidiate to the bottom (most nested) and in all of this passing frequently i mess the order of positional arguments as there is no possibility of named arguments, and arguments list become big part of a code

Use closures: https://m3g.github.io/JuliaNotes.jl/stable/closures/

1 Like