# Square bracket setindex! in macro argument

**URL:** <https://discourse.julialang.org/t/square-bracket-setindex-in-macro-argument/1095>\
**Category:** General Usage\
**Tags:** question\
**Created:** [December 21, 2016, 6:09pm UTC](https://discourse.julialang.org/t/square-bracket-setindex-in-macro-argument/1095 "2016-12-21T18:09:22Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![GordStephen](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/gordstephen/32/364_2.png) [@GordStephen](https://discourse.julialang.org/u/GordStephen)\
**Post date:** [December 21, 2016, 6:09pm UTC](https://discourse.julialang.org/t/square-bracket-setindex-in-macro-argument/1095/1 "2016-12-21T18:09:23Z")

</div>

Hi all,

I’m using macros to generate functions with repetitive structure (in this case, modifying one or more vectors in place). The following works well:

```julia
macro mymacro(ex)
    return quote
        for i in eachindex(Y)
            y = Y[i]
            $ex
        end
    end
end

myfunction!(X, Y, a) = @mymacro(setindex!(X, a + y, i))

```

But ideally, I would use square bracket syntax instead of explicitly calling `setindex!`:

```julia
myfunction2!(X, Y, a) = @mymacro(X[i] = a + y)

```

Unfortunately, in that case expanding the macro throws the following error:

```julia
 ERROR: LoadError: syntax: unhandled expr (kw (call getindex X i) (call + a #96#y))
 in eval_user_input(::Any, ::Base.REPL.REPLBackend) at ./REPL.jl:64
 in macro expansion at ./REPL.jl:95 [inlined]
 in (::Base.REPL.##3#4{Base.REPL.REPLBackend})() at ./event.jl:68

```

So it seems `X[i]` is being parsed into a `getindex` instead of a `setindex!`. Is this a fundamental macro / parsing limitation or is there something I can do to avoid it? Or is this a misdiagnosis of the problem?

Thanks,  
Gord

---

<div class="post-metadata">

**Author:** ![yuyichao](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/yuyichao/32/20_2.png) [@yuyichao](https://discourse.julialang.org/u/yuyichao)\
**Post date:** [December 21, 2016, 6:34pm UTC](https://discourse.julialang.org/t/square-bracket-setindex-in-macro-argument/1095/2 "2016-12-21T18:34:25Z")

</div>

This is caused by `@m(a = b)` parsing as keyword argument. IIUC `@m a = b` should be parsed as `=` instead. You can do the transformation by tranlating `Expr(:kw)` into `Expr(:(=))` with the same arguments.

Also note that you might want to properly escape the expressions.

---

<div class="post-metadata">

**Author:** ![GordStephen](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/gordstephen/32/364_2.png) [@GordStephen](https://discourse.julialang.org/u/GordStephen)\
**Post date:** [December 21, 2016, 6:45pm UTC](https://discourse.julialang.org/t/square-bracket-setindex-in-macro-argument/1095/3 "2016-12-21T18:45:11Z")

</div>

Ah, thanks.

```julia
myfunction3!(X, Y, a) = @mymacro X[i] = a + y

```

works as expected.
