As far as I could understand from the documentation and several posts on the web, the statement
include("myfile.jl")
just takes the code in myfile.jl and pastes it on the calling file (or in the console), replacing the line with the include statement.
Please correct me if I am wrong. I am just beginning with Julia. However, I have also seen the following comment by one of Julia's creators:
"include works in the dynamically-current module, not the lexically-current one.
It is really a load-time function, not a run-time one."
What is the difference between dynamically-current and lexically-current?
It's not a function call because if myfile.jl
is just a = 2
and you do include("myfile.jl")
, then you can check in the REPL that a = 2
. In functions that a
would have been defined in a different scope, and then erased after the function is ended. So this is a clear difference in behavior. Here's an example REPL session demonstrating the difference:
julia> a
ERROR: UndefVarError: a not defined
julia> function incl(file)
a = "not 2"
include(file)
@show Main.a
@show a
end
incl (generic function with 1 method)
julia> incl("myfile.jl")
Main.a = 2
a = "not 2"
"not 2"
julia> a
2
This is what they mean by "dynamically-current" vs "lexically-current". Lexically, a function runs in its own scope which is only accessible from within the functions actual code – there is no other way to access or change local variables. include
always runs at the current global scope even when called from inside of a function. Julia's eval
function behaves similarly – you cannot see or change local variables with eval
only global ones.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With