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

Re: Load autoloadable function, but only in enclosing function scope



On Thu, Mar 24, 2022 at 10:06 AM Peter Stephenson
<p.w.stephenson@xxxxxxxxxxxx> wrote:
>
> With that key limitation --- if you've already got functions with the
> names of the ones you're creating, you're stuffed --- you can automate
> it like this.
>
> fn() {
>   local -a oldfuncs=(${(k)functions})

It actually can be even shorter than that, depending on how carefully
the context needs to be preserved.  Peter's example keeps the
definitions of any functions that were previously defined, even if
those definitions were replaced (by autoload execution or explicit
redefinition).  The example below restores all the function
definitions to their previous state, even when replaced.  (Native zsh
mode semantics assumed below.)

foo() { print original foo }
bar() {
  local funcs=(${(kv)functions}
  {
    foo() { print the bar foo }
    foo
  } always {
    functions=($funcs)
  }
}

% foo; bar; foo
original foo
the bar foo
original foo

This does have side-effects for autoloaded functions; they become
defined with "builtin autoload -X" as the body, which doesn't always
work the same way as a true autoload.




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