Closure strange behaviour

Hello,

I’m experiencing the following unexpected behaviour. Imagine you have a function like:

function select_function(p)
    
    if p == "a"
        
        function a()
            println("a")
        end
        
    elseif p == "b"
        
        function a()
             println("b")
        end
        
    end
end

I would expect that :

select_function("a")()
a

Instead I get:

select_function("a")()
b

Moreover, I get the following error:

select_function("b")()
UndefVarError: a not defined

Stacktrace:
 [1] select_function(::String) at .\In[9]:11
 [2] top-level scope at In[13]:1
 [3] include_string(::Function, ::Module, ::String, ::String) at .\loading.jl:1091

May someone explain the logic behind it?

Thanks in advance

1 Like

See Defining a function inside if...else..end NOT as expected?

4 Likes