Variable not defined in module

Snipaste_2020-07-15_15-50-24

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

The code above doesn’t work. Is something wrong?
Julia version 1.4.2.

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

Just complementing what @Pbellive said, I am not sure of what you are trying here. Because:

  1. sum is already a name of a function in Base, and you are shadowing it. It is not a very good name to use, specially inside a module.
  2. You are making a loop just inside a module, not inside a function inside the module, are you sure this is what you want?

Thank you very much.

Thanks for complementing. I am learning about pre-compilation in Julia, my code is revised from a high voted answer in StackOverflow.

Ah, ok, it makes sense. The objective is exactly to do nothing except waste time, so the difference of time in the precompilation and post-compilation times is easier to see. It is just kinda of a strange code to see outside of this context.