Repeated section of code

Hello,
I have certain parts of my code that show up in a lot of functions. They are simple blocks of math like:

a=x+2
b=a+3
...

And a and b are later used in different ways. One way of doing this is like this:

function fun(x)
a=x+2
b=a+3
return a,b
# later in the code
a,b=fun(x)

but this gets cumbersome fast, as I have a lot of variables that are used and defined, plus a lot of them are StaticArrays and the whole thing gets a bit messy.

Is there some command to tell the compiler to insert a block of code into a function and that everything that gets declared/modified in that block is later seen by the function? Not with global variables, as most of these chunks create local variables that are used within parallelized for loops.
Performance is important.
Thanks!

You can do this with macros. But I would personally find such a solution much messier than a proper use of functions. I think it’s much better to use functions, and if you have many variables that are used in many places, consider using named tuples or custom struct types.

4 Likes

Thanks. I couldn’t figure out a way to have a macro that puts variables in the scope where it’s called. I know you can make a variable in a macro global, but what I’d like is something like:

function fun(x)
  for i=1:N
    @mac(x)
    vec[i] = a+b
  end
end
macro mac(x)
  a=2*x
  b=3*a
end

where a and b are available to use within the scope of the for loop, but not outside of it (and the for loop can be multi threaded).
Is this doable?

Linking this related thread.

Maybe you wanted to define the macro as follows:

macro mac(x)
    quote
        a=2*$x
        b=3*a
    end |> esc
end
2 Likes

Works like a charm and it’s fast! Thanks!