2

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 Commented Nov 17, 2020 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
    Commented Nov 17, 2020 at 6:03
  • @TeddyC It doesn't work since you're not calling inner_func from within outer_func, like Andy said.
    – Kusalananda
    Commented Nov 17, 2020 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
    Commented Nov 17, 2020 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. Commented Nov 18, 2020 at 1:39

1 Answer 1

2

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: You don’t need to use a local variable there. You can just use positional parameters instead:

outer_func() {
  inner_func 'test'
}

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

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .