Hello, guys! I am new to Julia. Help me please. I want to change my string initialized in upper local scope, and then use it there
text = "abacaba"
text_result = "" #string must be changed
for rule in 1:5
if i % 2 == 1 #some condition
text_result = replace(text, "a" => "b", count=1) #this is another string
end
end
print(text_result) # empty string will be printed
If the loop is not inside a function you need to declare test_results as a global AFAIK:
text = "abacaba"
text_result = "" #string must be changed
for rule in 1:5
if i % 2 == 1 #some condition
global text_result = replace(text, "a" => "b", count=1) #this is another string
end
end
print(text_result) # not empty string will be printed
The best advice is to use Jupyter, which does not have this issue. The code will work the way that is intuitive. Otherwise, put any for loops in a function when working in the REPL or a .jl file.
If you follow those rules and ever have to write global, then (as a beginner) you are probably are doing something you shouldnāt
Nah, this is not āthe best adviceā. The best advice is exactly what happened here, someone learned about what a global variable is and how to change itās binding and then went on coding exactly as before. There is absolutely no need to completely change your coding environment because of this.
The best advice is to make a new user learn about a complicated and frequently hated scoping rule that is only beloved by people who commit to core compiler? Furthermore, one which is completely alien to every other language the user may come from?
Or, alternatively, get started in a the beginner friendly environment and hope people eventually fix this problem - as has been discussed for a year.
I stick with my advice: Use jupyter, and wrap things in functions when you are not in jupyter.
Sorry if we seem to be jumping all over you here, but bear in mind, there are some of us who absolutely detest Jupyter, I donāt think itās a great idea to give people the impression that there is somehow something wrong with Julia outside of Jupyter. Of course, if someone wanted to use it anyway, itās great to present it as an option.
Complicated? It took one sentence and the reply was marked as a solution. Anyway, I am not going to pollute this thread further, I just didnāt want a bad advice stand uncontested.