Get closure with GetNewClosure

Get closure with GetNewClosure

  • Comments 4

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

Leave a Comment
  • Please add 7 and 2 and type the answer here:
  • Post
  • 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

    1

    2

    PS C:\> f2 1 2 4

    1

    2

    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.

  • I'm in Powershell 4 and this feature is still a mess. Functions I brought into the scope with the dot operator prior to creating the closure are not seen inside the closure.

Page 1 of 1 (4 items)