I have a main function as below:
include(“hello.jl”)
import .hello
rms = 0.0
hello.foo(rms)
println(rms)
and hello function is as below:
module hello
function foo(rms)
rms = 1.0
println(rms)
end
end
If i run the main.jl I get the output as 1.0 and 0.0. So the variable rms does not get changed by the function hello. I think it is got to do with the scope of the variable. Is there a way I can modify the variable inside the function. I can modify an array but not the variable inside the function.
Variables defined within a function are local to that function, and, usually, they are regenerated with each call to the function. When people want to have a value that is alterable from one call to another, the common practice is to use an argument to that function to pass the current value and keep the changing value in a variable outside of the called function. Is there a reason that is not suitable for your purpose?
Alternatively, you can make the variable global to the module.
module Example
export example
var = 0.0
function example(increment)
global var
var += increment
return var
end
end
using .Example
example(1.0) # shows 1.0
example(1.0) # shows 2.0
Surrounding your code blocks in ``` makes them easier to read
main.jl
include(“hello.jl”)
import .hello
rms = 0.0
hello.foo(rms)
println(rms)
hello.jl
module hello
function foo(rms)
rms = 1.0
println(rms)
end
end
See this section of the the FAQ:
https://docs.julialang.org/en/v1.0/manual/faq/#I-passed-an-argument-x-to-a-function,-modified-it-inside-that-function,-but-on-the-outside,-the-variable-x-is-still-unchanged.-Why?-1
By the way, functions that change their arguments by Julia convention are appended by an exclamation mark, e.g. sort!(foo)
.
I recommend doing the tutorials on Juliabox.com