Modify function with macros

I would like to do modify a function inner scope with a macro.
My goal is to add blocks of specific code within a simulation loop. These blocks have to:

  • instantiate variables
  • interact with internal variables
  • update variables

My main function looks like this:

function main_loop(args..., kwargs...)
   x = 0. # an internal variable
   ## add block1

   for t in 1:1000
      ##  add block2 

My blocks will look like this:

foo = some_function(kwargs...)

x += t ## These variables are defined within the function only!
foo = some_other_function(x)

My idea would be something like:

macro add_code main_loop, args..., kwargs...)
   -> do the magic <-

I want to do this because I would like to define many of such blocks and apply them to the main simulation loop without replicating it.

macro add_code1 main_loop, args..., kwargs...)
   -> do the magic <-

macro add_code2 main_loop, args..., kwargs...)
   -> do the magic <-

new_function1 = @add_code1 main loop <stuff>

new_function2 = @add_code2 main loop <stuff>

Is this possible at all?

Probably you don’t want a macro. Pass callback functions to your simulation loop instead.

1 Like

yeah, but I have to write very crap code then.

Also, if different blocks define different variables - it is the case- then this is not effective.

I am thinking about defining the main loop as a quote and define place-holder variables that I can use to other pieces of code.
Is this feasible?