Strange behavior of setindex() inside a function or a loop?

I’m not sure if this is a known issue or I’ve missed something obvious, but the following functions didn’t work as I expected. f() works correctly without a return value, but once I add return tt I get the original tuple without any values changed. The same happens if setindex is used inside a loop.

julia> using StaticArrays

julia> function f()
           tt = ntuple(_->0,10)
           setindex(tt,50,2)
       end
f (generic function with 1 method)

julia> f()
(0, 50, 0, 0, 0, 0, 0, 0, 0, 0)

julia> function f2()
           tt = ntuple(_->0,10)
           setindex(tt,50,2)
           tt
       end
f2 (generic function with 1 method)

julia> f2()
(0, 0, 0, 0, 0, 0, 0, 0, 0, 0)

julia> function f3()
           tt = ntuple(_->0,10)
           for i = 1:length(tt)
               setindex(tt,i,i)
           end
           tt
       end
f3 (generic function with 1 method)

julia> f3()
(0, 0, 0, 0, 0, 0, 0, 0, 0, 0)

Tuples are immutable and hence tt is always a tuple of zeros in your examples.
The first function did return the return value of setindex, since it was the last executed statement of function, which is another tuple with a 50 at index 2.
If you want tt to be that tuple, you have to assign it like

tt = setindex(tt, 50, 2)
2 Likes

Makes sense, thank you.