SeeminglyScience / PSLambda

A runtime compiler for PowerShell ScriptBlock objects.
MIT License
61 stars 3 forks source link

Nested foreach statements throw when the enumerator is of a different type #20

Open SeeminglyScience opened 6 years ago

SeeminglyScience commented 6 years ago

Example code:

[psdelegate]{
    foreach ($a in 0..10) {
        foreach ($b in 'one', 'two') {
            $Host.UI.WriteLine($a.ToString() + $b.ToString())
        }
    }
} | % invoke

Throws

% : Exception calling "Invoke" with "1" argument(s): "At line:3 char:9
+         foreach ($b in 'one', 'two') {
+         ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Expression of type 'System.Collections.Generic.IEnumerator`1[System.String]' cannot be used for assignment to type 'System.Collections.Generic.IEnumerator`1[System.Int32]'"
At line:7 char:5
+ } | % invoke
+     ~~~~~~~~
+ CategoryInfo          : InvalidOperation: (PSLambda.PSDelegate:PSObject) [ForEach-Object], MethodInvocationException
+ FullyQualifiedErrorId : MethodInvocationError,Microsoft.PowerShell.Commands.ForEachObjectCommand

I'm probably reusing a variable somewhere I shouldn't when constructing the loop. Work around is to use the System.Linq.Enumerable extension methods, Array.ForEach (or similar), or a for statement.