Zsh Mailing List Archive
Messages sorted by:
Reverse Date,
Date,
Thread,
Author
Re: wheels within wheels
On Sep 29, 4:16pm, Ray Andrews wrote:
} Subject: wheels within wheels
}
} I just learned that it's possible to declare a function within another
} function. A strange liberty.
Interpreted language. Defining a function is just like executing any
other command, so you can do it anywhere a command is allowed. There
really isn't any such thing as "declaring" a function -- either it is
defined [the command that defines it has been *executed*, not merely
written out as part of some dormant code] or it isn't.
The "functions -u" aka "autoload" command is the closest there is to
"declaring" a function, but really it defines a function with an empty
body which is to be filled in later. This is inaccurately referred to
as an "undefined" function because that's shorter to say.
} Why would one want to, and what are the gotchas of doing so?
Consider it a sort of conditional compilation, if you need a comparison.
Like the _git and tetris examples in the autoload thread -- various
helper functions get defined only if/when the main function that needs
them is actually called.
In addition to what Kurtis says, a gotcha with nesting functions is
that every time the outer function is called, it re-defines the inner
functions (deletes the old definitions and re-create them). Remember,
interpreted language. Everything interesting happens at run time.
Therefore do not nest function definitions unless you understand very
well what they are doing.
} BTW Bart, any further word on where to find the latest manual?
You should use the manual for the version of zsh that you have. If you
start looking at the latest manual but you're not using the latest
shell, you may get just as much misinformation as if you're looking at
an older manual.
} hot of the press. Is this a 'git' sort of thing?
Yes.
On Sep 29, 7:55pm, Kurtis Rader wrote:
}
} In short: don't do it.
That's a bit too short. Nesting function definitions is exactly what a
lot of autoloadable functions do. The difference is that autoloadable
functions also redefine *themselves* this way, to change what happens
the second time the "same" function (in name only) is called.
} 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.
Here's a modification of that script:
function foo {
echo defining bar
function bar {
echo hello from bar
}
echo redefining foo
function foo {
echo hello from new foo
bar
}
# this looks like infinite recursion,
# but it is not, because foo was redefined
foo
}
# This will say "command not found"
echo calling bar before foo
bar
echo calling foo
foo
echo calling bar after foo
bar
echo calling foo again
foo
Messages sorted by:
Reverse Date,
Date,
Thread,
Author