Scope when using multiple modules

I am new at using Julia. I am writing a PDE solver. I would like to have a struct that stores all mesh/simulation variables that could then be accessed from other modules in my code. However, I am having some trouble with the result (due to issues related to scope of variables):
Here is the simplified code to mimic the issue:

I have three files: MyParams.jl, ModuleA.jl main.jl,

--------------- MyParams.jl --------------------
module MyParams
param_A =
end

---------------ModuleA.jl------------------------
module ModuleA
include(“MyParams.jl”)

function Set_Param_A(N)
push!(MyParams.param_A, N);
println("In ModuleA, size of param_A: ", length(MyParams.param_A));
end

end

--------------main.jl---------------------------
include(“ModuleA.jl”)
include(“MyParams.jl”)

ModuleA.Set_Param_A(10);
println("In main, size of param_A: ", length(MyParams.param_A));

My output is:
In ModuleA, size of param_A: 1
In main, size of param_A: 0

Two questions:

  • Why is size of param_A not 1, when accessed from main?
  • What is the best way to store simulation parameters/mesh that needs to be accessed and modified from other modules?

Thanks

When you include a file inside a module definition, all the contents of that file is loaded into the module scope. So, you have modules Main.ModuleA.MyParams and Main.MyParams, which the system considers different.

There have been discussions recently on how to organize code in such cases, you may find and try different suggestions to choose from:
(Writing functions for types defined in another module)
(What is the preferred way to use multiple files?)

Also, please see this topic (Please read: make it easier to help you) for tips on formatting.

3 Likes

Thank you for your help!