Multiple function names

Normally when you have multiple function names in a project, the last duplicate function name is used and the previous ones are ignored. Here’s a simple program that shows something different and unexpected to what I thought would happen. There are 3 draw functions, and each one gets executed. Apparently you can have multiple function names as long as they are nested. Once a function is executed, it replaces the previous function of the same name. The inside functions could be executed based on a variable name. I doubt if this has any use, but I found it interesting. I found this out when I formatted the program “Codea Timer” written by @AwesomeCodeaKid to make it easier for me to read. I guess you can learn something from a 9 year old. When you run this, the first draw function will run, then the second, then the third. I stop the third to prevent a lot of print statements.


function setup()
    fill(255)
    ct=0
end

function draw() -- draw 1
    background(0)
    print("running function draw 1")
    
    function draw() -- draw 2
        background(0)
        print("running function draw 2")
        
        function draw() -- draw3
            background(0)
            if ct<3 then
                ct=ct+1
                print("running function draw 3  count ",ct)
            end
        end

        print("end of function draw 2")
    end
    
    print("end of function draw 1")
end

your rule

Normally when you have multiple function names in a project, the last duplicate function name is used and the previous ones are ignored. 

is still applying here. Simply, due to the nesting, the draw is overitten only when it is applied, hence the behavior.

@Jmv38 What I meant was if I didn’t nest the 3 draw functions, only the last draw function would be executed. But it surprised me that each of the draw functions executes at least once. Before seeing this run, I would have expected that only the 3rd draw function would have executed.

@dave1707 I can see a use of this tho, if you want certain part of a function to only be executed the first time it’s run, you can nest it like this instead of having to use an extra variable to use as flag

also, interesting ‘fact’: no longer do we have the need for setup, we can now do it in the draw fuction as part of the first run xD

Tho in both ‘cases’ this would probably make the code less readable, and I wouldn’t see the need the use it like this myself

It has a kind of elegance, one-time initialisation without explicit state variables. Congratulations @AwesomeCodeaKid for the interesting code.

@stevon8ter I really like the idea of a first time call doing setup. I think that way is a lot cleaner and clearer than first use flags. Probably a clean way to do finite state machines, too!