Clarify how scopes work and their relations to runspaces#1
Clarify how scopes work and their relations to runspaces#1
Conversation
| - When code running in a runspace references a scoped item, PowerShell searches | ||
| the scope hierarchy it has access to looking for a name match. If it doesn't | ||
| exist, a new item is created in the current scope. If it finds a match, the | ||
| item is copied to the current scope. If you create an item in a scope, and |
There was a problem hiding this comment.
i think it's only copied into the new scope if you alter the value (it could be very resource intensive otherwise). Otherwise, we just reference it in the first parent scope in which it is found. I know that's what it did in v1, but I'm not sure about that now. Patrick may know.
There may be specific instance where we do copy (closures, i think), but I don't think it's the general case.
| Get-Variable -Scope global | ||
| ``` | ||
|
|
||
| A child scope doesn't inherit the variables, aliases, and functions from the |
There was a problem hiding this comment.
this is a confusing paragraph. I think it's the "inherit" term. When a reference is made to a variable, alias, or function, the current scope will be search, then if not found, the parent scope is search (in a chain all the way to global). If a variable is private in a parent scope, the search through the scopes will not resolve and the search will continue through the scope chain.
here's an example:
PS> cat /tmp/scop.ps1
function A {
"Setting `$funcAVar1 to 'i am function a'"
$funcAVar1 = "i am function a"
B
}
function B {
"in B before set -> $funcAVar1"
$private:funcAVar1 = "I've locally overwritten it - child scopes can't see me!"
"in B after set -> $funcAVar1"
C
}
function C {
"in C before set -> $funcAVar1 - should be the value set in function A"
$funcAVar1 = "my child scope will see this change"
"in C after set -> $funcAVar1"
D
}
function D {
"in D -> $funcAVar1 - should be the value set in function C"
}
A
PS> /tmp/scop.ps1
Setting $funcAVar1 to 'i am function a'
in B before set -> i am function a
in B after set -> I've locally overwritten it - child scopes can't see me!
in C before set -> i am function a - should be the value set in function A
in C after set -> my child scope will see this change
in D -> my child scope will see this change - should be the value set in function C
PS>Co-authored-by: James Truher [MSFT] <[email protected]>
|
Closing draft. |
Draft PR for feedback