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

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



> On 24 March 2022 at 16:29 Mikael Magnusson <mikachu@xxxxxxxxx> wrote:
> On 3/24/22, Zach Riggle <zachriggle@xxxxxxxxx> wrote:
> > Is there a way to
> >
> > myfunc() {
> >     autoload foo && foo
> > }
> >
> > Such that foo and any other functions it declares are local-scope only?
> 
> Functions are never scoped at all, so no. You can manually unfunction
> it afterwards (if there was already a function with a conflicting
> name, autoload returned success and you ran the wrong function
> anyway). If you don't need any other side effects from myfunc, you can
> run the whole thing in a subshell of course.

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})
  {
    # as a working example --- "autoload subfunc" would work fine
    subfunc() { print This is subfunc; }
    subfunc
  } always {
    local -a funcs=(${(k)functions:|oldfuncs})
    (( ${#funcs} )) && unfunction $funcs
  }
}

Note that this won't unfunction subfunc even if it was previously
marked for autoload, but not actually loaded.  (In any case
you'd probably want to mark it for autoload again, to be consistent,
so that's an exercise for the reader.)

If your functions are all being autoloaded, and your only interest
is in getting rid of functions that you've autoloaded specially for
this function --- so there's no actual name clash, you just might have
already marked the function for autoload and it'll stay loaded ---
that might be good enough.

pws




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