Local scope in for loops AGAIN

You’re recreating local local_u in every iteration of the loop, thus overwriting its previous value. The behaviour you experience is therefore to be expected.

Why not just wrap it in a function?

u = 10 # global scope variable

function foo(u)
    for k in 1:10
        u = k*10*u # could also write u *= k*10
        println("At the end of iteration $k local u is $u")
    end
end

foo(u)

This is much simpler and you don’t have to deal with the local keyword, reassigning, copying or anything else.

4 Likes