1

I have a zsh function that looks like this:

outer_func () {
    local LOCAL_VAR='test'
    inner_func () {
        echo "${LOCAL_VAR}"
    }
}

where $LOCAL_VAR is not available to inner_func.

I know that I can use eval to define inner_func so that it can access the value of $LOCAL_VAR, I wonder if there's another way to do it?

Edit: test on zsh 5.8:

$ cat test.zsh
outer_func () {
    local LOCAL_VAR='test'
    inner_func () {
        echo "${LOCAL_VAR}"
    }
}

echo 'executing outer_func'
outer_func
echo 'executing inner_func'
inner_func

$ ./test.zsh
executing outer_func
executing inner_func

$

Edit 2: Clarification: I actually use outer_func to set variables to a series of inner_funcs which are essential for the inner_funcs to work, and after the definition of outer_func, I need to call the inner_funcs.

5
  • 1
    Using zsh 5.8, using your example LOCAL_VAR is visible within inner_func if I call inner_func from outer_func Nov 17 '20 at 2:39
  • @AndyDalton I'm using zsh 5.8 but it doesn't seem to work on my Mac. :( See the screenshot above.
    – Teddy C
    Nov 17 '20 at 6:03
  • @TeddyC It doesn't work since you're not calling inner_func from within outer_func, like Andy said.
    – Kusalananda
    Nov 17 '20 at 14:44
  • @Kusalananda Thanks for the info. What if I need to call inner_func directly, not from within outer_func? (See Edit 2)
    – Teddy C
    Nov 17 '20 at 15:58
  • 1
    Whenever you run inner_func, it's going to use a variable named LOCAL_VAR that is in scope (if one exists). I think eval is going to be your best bet. Nov 18 '20 at 1:39
1

There is no such thing as an "inner function" in Zsh. What your outer_func does is, each time it gets called, it creates a normal function inner_func that is publicly available (and which will overwrite any existing function called inner_func). However, your outer_func does not actually call inner_func. It merely creates it.

What you probably want is this:

outer_func () {
  local LOCAL_VAR='test'
  inner_func
}

inner_func () {
  echo "${LOCAL_VAR}"
}

Then, when you call outer_func, the result will be that inner_func echoes test.


PS: It would probably be better to re-write that code like this:

outer_func() {
  inner_func 'test'
}

inner_func() {
  print - "$1"
}
1
  • @TeddyC Does this answer your question? Dec 25 '20 at 18:27

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.