Quantcast
Channel: First steps - JuliaLang
Viewing all articles
Browse latest Browse all 2795

Included code behaves different than code in place

$
0
0

Included code behaves different than code in place

In file test.jl:

module test

function sumto(n)
    s = 0 
    for i = 1:n
        s = s + i 
    end
    s 
end

end # module test

This works:

julia>include("test.jl")
julia> test.sumto(5)
15

But if put the content of the function in a different file and include it I get an error.

In the file test2.jl

module test2

function sumto(n)
    include("test3.jl") 
end

end # module test

in file test3.jl:

    s = 0 
    for i = 1:n
        s = s + i 
    end
    s 
julia>include("test2.jl")
Main.test2
julia> test2.sumto(5)
┌ Warning: Assignment to `s` in soft scope is ambiguous because a global variable by the same name exists: `s` will be treated as a new local. Disambiguate by using `local s` to suppress this warning or `global s` to assign to the existing global variable.
└ @ C:\Gerhard\Model\Julia\MarketFlow\src\test3.jl:3
ERROR: UndefVarError: n not defined
Stacktrace:
 [1] top-level scope at C:\Gerhard\Model\Julia\MarketFlow\src\test3.jl:2
 [2] include(::Function, ::Module, ::String) at .\Base.jl:380
 [3] include at .\Base.jl:368 [inlined]
 [4] include at C:\Gerhard\Model\Julia\MarketFlow\src\test2.jl:1 [inlined]
 [5] sumto(::Int64) at C:\Gerhard\Model\Julia\MarketFlow\src\test2.jl:6
 [6] top-level scope at REPL[2]:1

I do not understand the warning since s is only a local variable in a function.
And I do not understand the error. Why ist “n not defined”?
If include just works as if the code is in the place where the include command is placed, should just work as in the original test file.

I am using:

 julia> versioninfo()                                                                    
 Julia Version 1.5.3                                                                     
 Commit 788b2c77c1 (2020-11-09 13:37 UTC)                                                
 Platform Info:                                                                          
   OS: Windows (x86_64-w64-mingw32)                                                      
   CPU: Intel(R) Core(TM) i7-8650U CPU @ 1.90GHz                                         
   WORD_SIZE: 64                                                                         
   LIBM: libopenlibm                                                                     
   LLVM: libLLVM-9.0.1 (ORCJIT, skylake)                                                 
 Environment:                                                                            
   JULIA_PKG_DEVDIR = C:\Gerhard\Model\Julia\MarketFlow\src                              
   JULIA_EDITOR = "C:\Users\totschnigg\AppData\Local\Programs\Microsoft VS Code\Code.exe"
   JULIA_NUM_THREADS =          

4 posts - 3 participants

Read full topic


Viewing all articles
Browse latest Browse all 2795

Trending Articles