Variable declaration without assignment

Hi, I have a question about what happens internally, when variables are declared without actually assigning a value, e.g., if I have a function like

function myfunc()
    local x
end

does this actually create a variable or does it just tell the compiler “Should a variable x be accessed within this scope, it should be a local variable” ?

After all, if I try to access this variable, e.g., by

function myfunc()
    local x
    x
end
myfunc()

I obtain an UndefVarError, which indicates that the variable has not actually been declared.
The fact that the actual position of local x in the method does not play a role seems to support this thesis, i.e., that the following code still throws an error:

x = 2
function myfunc()
    x
    local x
end
myfunc()

Maybe I am lacking some understanding here. I would appreciate any clarifications that help understanding what is actually happening under the hood.

It’s declared, yet it’s undefined. It just means it wasn’t assigned an instance yet.

julia> global x2
julia> hasproperty(@__MODULE__, :x2)
true
julia> isdefined(@__MODULE__, :x2)
false
julia> getproperty(@__MODULE__, :x2)
ERROR: UndefVarError: x2 not defined

Declarations apply to the whole scope, they’re not something that’s evaluated by line order. That first x is thus local, and evaluating it throws an error because there’s no instance.

5 Likes

Many thanks for the quickly reply. That clarifies everything!