My workflow is to usually have a init.jl file which brings some variables into scope, e.g. saveDir = "/path". Then all my scripts start with include("init.jl"). However, I noticed that this wasn’t always working, so I ended up doing global saveDir = "/path" (I know this is terrible practice, but hence the question).
I just tried to prove this to myself with a small example, but wasn’t able to get it to work. I thought it may have something to do with the fact that I ran include from a script and not the REPL, but I that wasn’t the case either. I feel like I couldn’t have imagined this behaviour - has anyone else experienced this? Or has an explanation for when and why this happens?
Thanks! Would a loop be “equivalent” to a function? And if that’s the case, any ideas on how to circumvent that? My initial thought was to save a .jld2 file and then load it every time I needed it.
If init.jl is defining some constant global variables, well, just do that globally. If the variables it define changes based on the caller, use a function instead.
Apologies to re-open this, but I realised that this probably relates to another problem I have sometimes.
Often I define a parameter before entering a for loop:
important_param = 5
for i = 1:5
x = i + important_param
end
However, sometimes (and for reasons I haven’t been able to fathom) julia complains that important_param is undefined, so I have to do this:
let important_param = 5
for i = 1:5
x = i + important_param
end
end
This literally pops out of nowhere sometimes, and I assume it’s due to me misunderstanding how scoping works in Julia. Any ideas? Or should I look at / open another thread?
I have answered my own question, having found a bunch of threads on the issue e.g. this one. For my next project I will take the advice of writing everything in functions (though the claim that “The new debugger works like a charm” does not line up with my experience when I tried it back then). For now I’m going to keep putting global everywhere as if my life (or more realistically a deadline) depended on it.