# Macro to generate do block

**URL:** <https://discourse.julialang.org/t/macro-to-generate-do-block/23324>\
**Category:** General Usage\
**Tags:** question\
**Created:** [April 19, 2019, 8:23pm UTC](https://discourse.julialang.org/t/macro-to-generate-do-block/23324 "2019-04-19T20:23:06Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![MaxPauer](https://avatars.discourse-cdn.com/v4/letter/m/94ad74/32.png) [@MaxPauer](https://discourse.julialang.org/u/MaxPauer)\
**Post date:** [April 19, 2019, 8:23pm UTC](https://discourse.julialang.org/t/macro-to-generate-do-block/23324/1 "2019-04-19T20:23:06Z")

</div>

I use a lot of code that looks like this

```julia
foo(arg1, arg2) do bar
   bar.this = 5
   bar.that = 6
end

```

What I initially wanted to do is replace the repetitive "bar"s by defining macros for “this” and “that”, which seems easy enough. This, however, relies on the argument actually being called “bar”. So I wanted to write a macro to generate the complete do-block as well.  
Now, I do realize this might not actually be a good idea as there is an obvious upside to explicitly defining the argument name. However, as I thought about it and I couldn’t get it to work, I got curious if it is actually possible.

So my question is, is there a way to make a macro like this (or similar) generate the code from above:

```julia
@foo arg1 arg2 begin
   bar.this = 5
   bar.that = 6
end

```

---

<div class="post-metadata">

**Author:** ![Tamas\_Papp](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/tamas_papp/32/25949_2.png) [@Tamas\_Papp](https://discourse.julialang.org/u/Tamas_Papp)\
**Post date:** [April 20, 2019, 5:31am UTC](https://discourse.julialang.org/t/macro-to-generate-do-block/23324/2 "2019-04-20T05:31:15Z")

</div>

Something like

```julia
using MacroTools

macro foo(a1, a2, block)
    @capture(block, begin body__ end)
    quote foo($(esc(a1)), $(esc(a2))) do $(esc(:bar))
        $(map(esc, body))
    end
    end
end

```

but I am 99% certain I got the hygiene/escaping wrong somewhere (because I always do); fix accordingly.

---

<div class="post-metadata">

**Author:** ![MaxPauer](https://avatars.discourse-cdn.com/v4/letter/m/94ad74/32.png) [@MaxPauer](https://discourse.julialang.org/u/MaxPauer)\
**Post date:** [April 20, 2019, 3:55pm UTC](https://discourse.julialang.org/t/macro-to-generate-do-block/23324/3 "2019-04-20T15:55:20Z")

</div>

Actually, it even worked without the capture magic like this:

```julia
macro foo(a1, a2, block)
	quote
		_foo($(esc(a1)), $(esc(a2))) do $(esc(:bar))
			$(esc(block))
		end
	end
end

```

…which I am fairly certain I tried yesterday as well, but it was late, I guess.  
Anyway, thanks for pointing me in the right direction 🙂
