Staufenbache
Staufenbache

Reputation: 25

Loading Module in Julia

i'm having some trouble loading module in Julia. I have to module that i cant load in my main file.

So my code (i'm trying to make an octree) look like this:

module Node
    
    export node, contains, intersect
    
    mutable struct node
        x::Float64
        y::Float64
        z::Float64
        m::Float64 
        node(x,y,z) = new(x,y,z,0)
    end
    
end # module

and my other module:

module Tree
        
    include("Node.jl")
    using .Node
        
    export tree, insert!, subdivide!
        
    mutable struct tree
            
        capacity::Int64
        node::node
        divided::Bool
        
        tree(capacity, node) = new(capacity, node, false)
    end
end

My problem is when i try to import the module in my main file using something like that:

include("Node.jl")
using .Node
include("Tree.jl")
using .Tree
    
plop=node(0,0,0)
plip=tree(1,plop)

I get the following error:

ERROR: LoadError: MethodError: Cannot `convert` an object of type node to an object of type Main.Tree.Node.node

I understand its due to the using .Node in my tree module which conflict with the same import in the main file but i'm unable to find a workaround.

One solution would probably be to put everything in the same module but i would like to keep thing separated.

Upvotes: 1

Views: 441

Answers (1)

Oskar
Oskar

Reputation: 1450

Well, you actually just put the two modules in the same module. Or to be more precise, you have a module Node and a module Tree with a submodule Node in it, thus the Main.Tree.Node.node. This happens because you use include("Node.jl") within your Tree module. The include function works as if it copied the text in the Node.jl file and pasted it into the Tree.jl file. Thus, to use the Node module within Tree without creating a submodule you have to add it.

So, I'd recommend you to generate a package for both the Node and Tree modules. This is done by

julia> using Pkg
julia> Pkg.generate("Node")
  Generating  project Node:
    Node/Project.toml
    Node/src/Node.jl

and then copy your Node.jl and Tree.jl files to replace the ones that were created. Then you can look at this question that tells you how to add a local package.

To sum it up you need to

julia> Pkg.develop(path="/Path/to/Node")
julia> Pkg.develop(path="/Path/to/Tree")

then your /Path/to/Tree/src/Tree.jl looks like

module Tree
    using Node
    [...]
end

and to run your code you can type

julia> using Node, Tree
julia> plop=node(0,0,0)
node(0.0, 0.0, 0.0, 0.0)
julia> plip=tree(1,plop)
tree(1, node(0.0, 0.0, 0.0, 0.0), false)

Note that it will probably tell you that Tree does not have Node in its dependencies. To solve that you might want to have a look at the documentation of Pkg.jl.

Upvotes: 1

Related Questions