Variable not defined in module

Hi @Lewis_Liu and welcome to the julia Discourse! The reason your snippet doesn’t work is because modules in julia introduce global scope and loops introduce local scope. Local scopes inherit variables from enclosing local scopes but not from global scope. I imagine those last couple of sentences might have been pretty confusing if you’re not very experienced with variable scoping. I would recommend reading through the section of the manual on variable scoping in order to get a thorough understanding, but here are a couple of quick examples to illustrate what I’m talking about:

If you want your example to work with minimal modification you need to use global variables:

module TestN1
    global sum=1
    for i in 1:10
      global sum += i
    end
end

However, that’s not necessary inside functions, which create their own local scope:

function testN1()
    sum=1
    for i in 1:10
       sum += i
    end
    return sum
end

In this case the function introduces a local scope and the for loop inherits variables from that enclosing scope.

2 Likes