Have you ever created scriptblocks on the fly, say in a foreach loop, and they totally mess up because they all have the same value?
This is something sort of advanced, and typically used when you’re proxying an object.
The most basic example would be, taken from (http://www.powershellcommunity.org/Forums/tabid/54/aff/1/aft/2506/afv/topic/Default.aspx)
function add([int]$x) { return { param([int]$y) return $y + $x } }$m2 = add 2$m5 = add 5&$m2 3 #expected: 5 actual: 3&$m5 6 #expected: 11 actual: 6
The value for $x is $null for both.
Why is that? Its because $x is $null in the local scope, the script block doesn’t remember the $x.
If we do
$x = 1000&$m2 3 #expected: 5 actual: 1003&$m5 6 #expected: 11 actual: 1006
This can be fixed in V2 using closures.
function add([int]$x) { return { param([int]$y) return $y + $x }.GetNewClosure() }$m2 = add 2$m5 = add 5&$m2 3 #expected: 5 actual: 5&$m5 6 #expected: 11 actual: 11
Closures are also great for ScriptProperties and ScriptMethods.
Hope this helps,Ibrahim
PingBack from http://www.anith.com/?p=23830
Why is lexcial scoping not the standard?
I think the language is a mess. (or maybe just the implementation?)
Example:
PS C:\> function f2($x,$y) { echo ($x,$y)}
PS C:\> f2 1
1
PS C:\> f2 1 2
2
PS C:\> f2 1 2 4
or
PS C:\> echo "val: $nix"
val:
PS C:\> echo "val:" + $nix
The variable $nix cannot be retrieved because it has not been set yet
At line:1 char:18
+ echo "val:" + $nix <<<<
Why the difference?
Is their some specification of this behaviour?
I don't get an error with that line. You probably have your strict setting set.