I’m not exactly “new to Julia” but I thought this would belong here.
How do you access a global variable hidden by a local variable of the same name? Reading the documentation (see the bottom of this message), I got the impression that global x
was the way, but I found that it’s an error once the global x
is hidden by the local one.
By just a guess, I discovered that Main.x
is accessible. So, is this the “official” way? Or is there a standard way to refer to the outer scope? Here is a sample code:
x = 123
function func(x)
@show x
x = "hello"
@show x
# global x += 321 # -> MethodError: no method matching +(::String, ::Int64)
Main.x += 321
@show x
@show Main.x
end
func(3.14)
[Now, please don’t mention 1) that using the same name is a bad practice or 2) that modifying a global variable is a bad design. I know that this is a bad practice and it’s a bad design in general. But, I have a legitimate use for this, but to describe it would double the length of this message. So, please assume that I know what I’m doing. ]
https://docs.julialang.org/en/v1/manual/variables-and-scoping/