How to pass all the variables defined within a function to a nested function?

Hi there,

I am trying to pass all the variables defined within a function (say foo) to a nested function (say bar) as arguments. Something along the lines of

function foo(arg1, arg2; kwarg1=1, kwarg2=2) 
    # do something
    bar(all variables within foo including arg1, arg2, kwarg1, kwarg2)
end

Is there a simple way to do it?

Perhaps return Base.@locals ?

Not the best way though, maybe pack them into a dict using Parameters, and then unpack them inside the function?

Kind regards

1 Like

Why do you wish to pass the local variables as arguments, when you can simply allow the inner function to capture them from its enclosing scope?

2 Likes

Adding to @uniment’s answer, the documentation on Scope of Variables might be helpful:

A scope nested inside another scope can “see” variables in all the outer scopes in which it is contained.

A new local scope is introduced by most code blocks…If such a block is syntactically nested inside of another local scope, the scope it creates is nested inside of all the local scopes that it appears within, which are all ultimately nested inside of the global scope of the module in which the code is evaluated. Variables in outer scopes are visible from any scope they contain — meaning that they can be read and written in inner scopes…

1 Like