PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Wednesday, August 24, 2022

[FIXED] How to use function that belongs to module 1 inside module 2?

 August 24, 2022     julia, module     No comments   

Issue

I'm trying to use a function that is inside a file (module 1) in another file (module) 2. But it gives me an error "ERROR: UndefVarError: t1 not defined". I have tried to export the function in module 1 but it also doesn't work. I'm new to Julia and I do not know very well how to handle modules. Here is the code that I'm having problems.

First File: t1.jl

module A
    function soma(a::Int64, b::Int64)
        return a + b
    end
end

Second File: t2.jl

module B
    include("t1.jl")
    using .t1

    function main()
        s = soma(2, 3)
        println(s)
    end

    main()

end

Solution

Changing t2.jl to:

module B
    include("t1.jl")
    using .A

    function main()
        s = A.soma(2, 3)
        println(s)
    end

    main()

end

prints out 5 as expected.

include is basically as if you'd copy-pasted the code from the included file into the current file - so, once you've included t1.jl into module B, the fact that the file is called t1.jl has no relevance. It's module A that's in the current scope, and A is the namespace that contains the soma function we need. Hence, using .A is what's needed to make soma available within B.



Answered By - Sundar R
Answer Checked By - Katrina (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing