Functions inside loops

Sorry for reviving an old thread, but I came across some difficulties regarding this topic and my google search lead me here.

Since OP didn’t post their code, we can’t be sure about what was their actual problem. However, as @baggepinnen pointed out, I think they might’ve been expecting something along the lines of what I reported here.

In my specific case, I had to redefine a function inside a nested loop. Before considering @baggepinnen use of anonymous functions, I thought about the the following solution. Basically it creates each function inside it’s own nested loop and then stores them in a vector of vectors, so that each function can then be accessed when needed.

n = 5
m = 2
funcs = Vector{Function}(undef, n)
funcs_arr = fill(funcs, m)

for i in 1:m
	funcs = Vector{Function}(undef,n)
	for j in 1:n
		f(x) = i^2+j
		funcs[j] = f
	end
	funcs_arr[i] = funcs
end

# Check Results
for i in 1:m
	for j in 1:n
		println(funcs_arr[i][j](1))
	end
end

#julia>
#2 
#3
#4
#5
#6
#5
#6
#7
#8
#9

I thought of leaving this for future reference and critique.
I also wonder which method would be preferred, this one or redefining anonymous functions, since I recall mentions of anonymous functions not being as fast as regular ones (but I’m not sure if that still holds as of Julia 1.3).