Variable Scoping in Non-Interactive Context

I’m trying to index a vector in a soft local variable scope, but I just can’t seem to do it. The code looks minimally something like this:

in a file called testfile.jl

struct TestStruct
    thing::Int64
end
function Foo()
    a = Vector{TestStruct}(undef,10)
    fill!(a, TestStruct(0)
    for i in 1:10
        a[i] = TestStruct(i^2)
    end
    return a
end

then, in a separate file called test.jl

include("testfile.jl")

println(Foo())

This gives the expected result, but in my proper code which is quite a bit more complicated doesn’t. In that instance (using assert statements to determine the issue), a is being returned as an array of TestStruct(0)'s, as if the for loop didn’t do anything. I think this is a scoping issue since if you check the value within the for loop, it gives the correct answer, but if you check the value out of the for loop, it doesn’t. However, from what I can tell, I’m writing the scoping correctly by wrapping it in a function, and given that the example here works as expected, I don’t know what could possibly be the issue.

Does anyone have any ideas on what could cause this, or otherwise what I can try to further diagnose it?

Best to come up with a minimal example that actually reproduces your difficulty. (Take your real code and keep deleting things a little at a time.)

2 Likes