I am trying to define a function that delegates a task to a set of internal, very similar subfunctions. These subfunctions need access to names in the scope of the defining function.
Sounds like a job for metaprogramming, but I have a hard time making it work. Here is an MWE:
# It works in global scope
for func in [:foo, :bar]
@eval function $(Symbol(string(func, "_func")))()
A[1] += 1
end
end
A = [0]
foo_func()
bar_func()
A # result 2
#But not if I wrap it in a function
function test()
for func in [:foo, :bar]
@eval function $(Symbol(string(func, "_func")))()
A[1] += 1
end
end
A = [0]
foo_func()
bar_func()
A
end
test() # result 0
This is clearly because @eval
evaluates to the global scope. So, I must not be approaching this the right way. What is the recommended approach for achieving this?
Thanks!