Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

change the contents of a global variable from another module in Julia

I have two modules, one called mainLoop and the other called subroutines:

module mainLoop
using subroutines
export memory
memory = zeros(Int,10)
foo(UInt32(17))
print(memory,"\n")

end

module subroutines
using mainLoop
export foo

function foo(x::UInt32)
  mainLoop.memory[1]=x
end
end

I can't figure out how to change the contents of the array called memory from the subroutine module. I don't have the option of passing the array as an argument to the function so I have to use a global variable. In the documentation, it states:

"Modules can introduce variables of other modules into their scope through the using or import statements or through qualified access using the dot-notation, i.e. each module is a so-called namespace. Note that variable bindings can only be changed within their global scope and not from an outside module."

By variable bindings, does it mean that you can't change the variable contents?

like image 249
JJTO Avatar asked Sep 27 '16 19:09

JJTO


Video Answer


1 Answers

A module can only change its own global variables, not those of other modules. There is a way, of course, to force a module to change its own global variables — by running toplevel code through eval.

julia> module A
           x = 1
           y = 2
       end
A

julia> module B
           using ..A
           println("A.x = ", A.x)  # can access
           A.y = 3  # can't set
       end
A.x = 1
ERROR: cannot assign variables in other modules

julia> A.y
2

julia> module C
           using ..A
           println("A.x = ", A.x)  # can access
           @eval(A, y = 3)  # set y = 3, FROM module A
           println("A.y = ", A.y)  # value of y updated
       end
A.x = 1
A.y = 3
C

julia> A.y
3

However, mutating global state — especially some other module's global state — is a code smell and should be avoided if at all possible.

like image 92
Fengyang Wang Avatar answered Sep 27 '22 17:09

Fengyang Wang