About Monkey 2 › Forums › Monkey 2 Development › Eachin is not by reference?
Tagged: RS Gold
This topic contains 5 replies, has 4 voices, and was last updated by 
 doaqwh 2 years, 3 months ago.
- 
		AuthorPosts
 - 
		
			
				
January 6, 2017 at 2:48 pm #6254
I find it confusing that Eachin seems to work on a copy of my collection and not looping through it as I expect it to, like it does im monkey-x and c#
Is this intended behaviour, and where do I read about it?
Example:
Monkey123456789101112131415161718192021222324Local points:= New Vec2f[2]points[0].x=10points[0].y=10points[1].x=20points[1].y=20Local off:= New Vec2f(7,6)' this one works'For Local i:Int = 0 Until points.Length' points[i] +=off'nextFor Local p:=Eachin pointsp +=offnextFor Local p:=Eachin pointsPrint "Result : " + p.x + " , " + p.ynextJanuary 6, 2017 at 3:19 pm #6257looks like you’re changing a local variable p not items in points…
see the Icontainer “interface” documentation, it shows you the code eachin gets converted into.
January 6, 2017 at 3:33 pm #6258looks like you’re changing a local variable p not items in points…
Yes, that’s what going on. However this Monkey-x code treats the p as a reference:
Monkey12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849StrictClass Vec2fField x:FloatField y:FloatMethod New(x:Float,y:Float)Self.x = xSelf.y = yEnd MethodEnd ClassFunction Main:int()Local points:Vec2f[2]points[0] = New Vec2fpoints[1] = New Vec2fpoints[0].x=10points[0].y=10points[1].x=20points[1].y=20Local off:= New Vec2f(7,6)' this one works'For Local i:Int = 0 Until points.Length' points[i] +=off'nextFor Local p:=Eachin pointsp.x += off.xp.y += off.ynextFor Local p:=Eachin pointsPrint "Result : " + p.x + " , " + p.yNextReturn 0End FunctionJanuary 6, 2017 at 4:22 pm #6262The difference (not your nickname:) ) is: in mx2 vec2f is a struct but it is a class in mx1. struct is copied when assign it to var.
If you define vector as a class in mx2 it will be changed by the way you shown above.
January 6, 2017 at 6:58 pm #6264Thanks nerobot. That makes sense, and explains the behaviour.
January 7, 2017 at 3:08 am #6269Would you like to be friends with me?
Can we be friends?
RS Gold to you at http://www.rsgoldfast.com/
 - 
		AuthorPosts
 
You must be logged in to reply to this topic.