Global access from within module function

Hi guys

why does the following not work and how can one fix it?

module MyModule

    x = 5
    
    function func(x)
        return (global x) + x
    end

end


using .MyModule
MyModule.func(3)

It gives syntax: misplaced "global" declaration

The global can be used to overwrite the global variable x, but read-only access is not possible?

Cheers!

That’s just a syntax issue. You could do this:

julia> module MyModule

           x = 5
           
           function func(x)
               global x
               return x + x
           end

       end

(but don’t do it :stuck_out_tongue: , as you’ll see, the result of func(3) is 10, and that’s a mess)

1 Like

So one cannot use both the global and the local x and would have to rename one of them?

1 Like

To be sincere, using the same name would be so prone to problems that I never tried that. But I guess there is way to do It.

Correct. Variable scope declarations actually happen across the whole scope at once, they don’t run in order like operations and calls. Hence this:

julia> x = 5
5

julia> function func(x) # local x
         result = x+x # uses global x
         global x
         return result
       end
func (generic function with 1 method)

julia> func(3)
10

The error is because global x is a variable declaration (can be left side of an assignment), not an access of a value (can be right side of assignment).

julia> function getx()
         global x # only left side, lack of value
       end
ERROR: syntax: misplaced "global" declaration
Stacktrace:
 [1] top-level scope
   @ REPL[17]:1

julia> function getx()
         global x = 5 # 5 on right side as value
       end
getx (generic function with 1 method)

julia> function getx()
         global x
         x # not a declaration, just accesses the value
       end
getx (generic function with 1 method)
3 Likes