Includes and loops

I have defined some code (generation of a mesh) in a file “mesh.jl” that I’m trying to include in an other one. The command include("mesh.jl") worked fine. To draw a convergence curve I tried to use it into a loop and get the error “UndefVarError: k not defined”.

Here is a MWE:

for i=1:10
	k=3
	include("bug2.jl")
end

and bug2.jl is a one liner:
N=2^k

How could I fix this?

Thanks for reading this far,
Best,
Benoît

This is not a bug.

My understanding is that include operates in the global scope using essentially the same mechanisms as eval. By design, Julia is not intended for this sort of locally scoped file inclusion stuff because it’s just generally a bad way to write code.

If you want to do something like this, you should change bug2.jl to contain a function:

N(k) = 2^k

and then write

include("bug2.jl")

for i=1:10
	k=3
    N(k)
end
9 Likes