1

Say I have a child function.

function hello {
$x= 1
$y = 2;    
}

function outerFunction {

hello

$z = $x + $y

}

Is it possible to somehow do this?

4
  • 3
    Yes, you just need a dot before the function call: . hello Commented Mar 24, 2022 at 15:50
  • 1
    Can also set the scope of the variables, but Santi's suggestion is the way I'd take as well. Commented Mar 24, 2022 at 15:52
  • @AbrahamZinala: Can you show how? Commented Mar 24, 2022 at 16:27
  • 1
    so, inside your function you would set the scope of the variables: $script:x = 1. Then when you call on hello, you would load $x into the script scope making it available to you. Commented Mar 24, 2022 at 17:15

1 Answer 1

1

You can use the Dot sourcing operator . to bring the variables defined in the scope of the hello function to the scope of outerFunction function:

function hello {
    $x = 1; $y = 2
}

function outerFunction {
    . hello
    $x + $y
}

outerFunction # => 3

You could also consider a different alternative depending on your use case, where the operator is not involved. For example:

function hello {
    1, 2
}

function outerFunction {
    $x, $y = hello
    $x + $y
}

outerFunction
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.