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

I took Mason’s advice to heart, and ended up not needing to do this dirty include in loop for several years. I do now (the call in a loop is done for debugging, otherwise it is a true script that will be run only once per julia session), thus I have created this small function that does it:

using Printf
using Random

function include_as_function(scriptname,argsname=[])

	header=@sprintf("function %s(",scriptname)
	for n in argsname
		header *= n * ","
	end
	header=chop(header)
	header*=")\n"


	functionfile=@sprintf("%s/%s_%s.jl",pwd(),scriptname,randstring(24))
	scriptfile=@sprintf("%s/%s.jl",pwd(),scriptname)

	
	s=open(functionfile,"a+")
	write(s,header)
	write(s,read(scriptfile))
	write(s,"end")
	close(s)
	
	include(functionfile)
	rm(functionfile)
end