Zsh Mailing List Archive
Messages sorted by: Reverse Date, Date, Thread, Author

Re: wheels within wheels



On Tue, Sep 29, 2015 at 4:16 PM, Ray Andrews <rayandrews@xxxxxxxxxxx> wrote:

> I just learned that it's possible to declare a function within another
> function.  A strange liberty.  Why would one want to, and what are the
> gotchas of doing so?
>

Many compiled languages support the concept of "closures". Even those, like
Python, which are compiled on the fly into byte-code as they are executed.
On the other hand zsh, and in general any shell, based on bash or csh do
not support closures or namespaces so I have no idea why someone would nest
function definitions in those shell languages. Google "zsh closures" and
read this answer:

http://unix.stackexchange.com/questions/94129/is-there-something-like-closures-for-zsh


In short: don't do it. You can see for yourself that nested, named,
function definitions are in fact globally visible (as opposed to visible
only to the function in which they're defined) by executing the following
script. Anonymous functions defined within another function are a different
matter but outside the scope of this question.

I've seen some pretty amazing bash/csh/ksh/zsh scripts in my life.
Including one that implemented an assembly language compiler. But if you
need that level of complexity you should be using a different language. If
the only tool you know how to use is a hammer then every problem looks like
a nail.

#!/bin/zsh

function foo {
    function bar {
        echo hello from bar
    }

    echo hello from foo
    bar
}

echo calling foo
foo
echo calling bar
bar

-- 
Kurtis Rader
Caretaker of the exceptional canines Junior and Hank


Messages sorted by: Reverse Date, Date, Thread, Author