3
votes

In Julia, all variable assignments in a function are local by default, but you can use the global keyword to assign to a global variable instead. How to assign to a variable to an outer but non-global scope?

2

2 Answers

3
votes

There isn't currently any way to do this. We've occasionally discussed it, since it's the one scoping behavior you can't do, but I've yet to see a really compelling reason to need it. Do you have one?

0
votes

I want to generate some code and have it executed using the include_string command:

Unfortunately, the 'global' keyword does not really have any effect on variables that are scoped within the file in which a module is defined (outside the module def). If a variable is scoped outside of the module, In My Hands, only passing it into the function directly, gives one access to it.

Like So:

module my_mod

function IDontWork(x:int)
    global mp
    include_string("Show(mp)") 
end #function  IDontWork

function IWork(x:int, mp::Minipipe)
     include_string("Show(mp)") 
end #function IWork

function Show(mp::Minipipe)
     println(mp.txt) 
end #Show 
end #my_mod

#mp declared in global scope: 
mp = Minipipe()

#FAILS: 
my_mod.IDontWork(2)

#Only Way it WORKS: 
my_mod.IWork(2, mp)

My answer is also a question: Am I using the global keyword correctly here? Is there a better way to do this??