blitz-foundation / monkey2

zlib License
3 stars 0 forks source link

Missbehaviour with EachIn on arrays #95

Open Pharmhaus-2 opened 5 years ago

Pharmhaus-2 commented 5 years ago

Original Author: madgician-vd

Hello!

I noticed a weird behaviour when using a simple array (array of basic variable type, or array of simple struct).

When using: For Local i := 0 to Array.Length - 1 .. Next it acts as intended... But when using: For Local t := EachIn Array ... Next

it doesn't affect the array contents... So it seems that it affects the array's item CONTENT to t instead of it's pointer, which seems odd to me, since when we use EachIn, it sounds obvious we want the pointer to be affected, so we can both read and write the array content.

Here is a little simple "labtest" to demonstrate it:


Namespace test
    #Import "<std>"
    #Import "<mojo>"

    Using std..
    Using mojo..

    Struct Test
        Field X:Int = 0
        Field Y:Int = 0
    End Struct 

    Global instance:AppInstance
    Global test:Test
    Global X:Int = 0
    Global Y:Int = 0

    Global structarray:Test[] = New Test[1]
    Global nonstructarray:Int[] = New Int[1]

    Class MyWindow Extends Window

        Method New()
            Super.New("Test", 320, 200)
        End Method

        Method Update()
                If Keyboard.KeyReleased(Key.Escape) Then instance.Terminate()
                structtest(test)
                structtest(structarray[0])
                nonstructtest(X)
                Y += 1
                test.Y += 1
                structarray[0].Y += 1
                For Local t := Eachin structarray
                    t.X += 1
                Next
                For Local t := Eachin nonstructarray
                    t += 1
                Next
        End Method

        Method structtest(t:Test)
            t.X += 1
        End Method 

        Method nonstructtest(t:Int)
            t += 1
        End Method 

        Method OnRender( canvas:Canvas ) Override
            App.RequestRender()
            Update()
            canvas.DrawText("Struct.X: " + test.X, 10, 10)
            canvas.DrawText("Struct.Y: " + test.Y, 10, 22)
            canvas.DrawText("Non Struct X: " + X, 10, 34)
            canvas.DrawText("Non Struct Y: " + Y, 10, 46)
            canvas.DrawText("Array of Struct X (EachIn): " + structarray[0].X, 10, 58)
            canvas.DrawText("Array of non-Struct (EachIn): " + nonstructarray[0], 10, 70)

        End Method

    End Class

    Function Main()
        instance = New AppInstance
        New MyWindow
        App.Run()
    End Function

End Namespace 

So, is this an issue ? Or is a such behaviour intended for some reasons ?