For what i understand (and is not a lot), there is a problem with the scope of the function, as the variables inside the loop can’t access variables outside the loop (for more information, you can read this discourse thread New Scope Solution ). One way is to directly use the variable using the global
prefix:
x = 0
for i = 1:5
global x += 1
println(x)
end
But I recommend using directly the iterator:
for i = 1:5
println(i)
end
If you really need to use that x
, you can make a function:
function myfn(x)
for i=1:5
println(x+i)
end
end
so, you have this
julia> myfn(2)
3
4
5
6
7
if you want the x modified, you can do something like this
function myfn!(x)
#in julia, the ! means that the function modifies the argument, generally the first one
for i=1:4 # the return statement prints x
x+=1
println(x)
end
return x
end
julia> x = myfn!(0)
1
2
3
4
5
julia> x
5