I want a function that returns a function that stores and uses the argument to the first function. An example should help clarify:
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
After a little debugging I found that when add 2 executes the value of $x -eq 2 but when the returned script block is executed $x -eq $null.
A simple workaround is to evaluate $x and then use Invoke-Expression to create the script block:
function add([int]$x)
{
return Invoke-Expression "{ param([int]`$y) return `$y + $x }"
}
$m2 = add 2
$m5 = add 5
&$m2 3 #actual: 5
&$m5 6 #actual: 11
Notice I had to escape $ to make this work. If I was concatenating strings I'd have to use something like return `$y + '$x'. I don't see this approach working well for all objects.
Is there anyway to get closures in PowerShell v1.0?