eachin 2d array[][]?

Monkey Forums/Monkey Beginners/eachin 2d array[][]?

dubbsta(Posted 2017) [#1]
trying to change the value in a 2d array

this works
map[3][5] = 1

this doesnt
for local i:= eachin map
for local j:= eachin map
map[i][j] = 1
end
end
???


Phil7(Posted 2017) [#2]
It is a little bit confusing, but you have arrays in arrays and not 2d arrays like in other languages.

So you have to do it like:
  for local j:= eachin map[i]


... as map[i] is one of the inner arrays (btw. not tested)


dubbsta(Posted 2017) [#3]
no doesnt work i not declared


Phil7(Posted 2017) [#4]
My fault. You have to options of dealing with arrays. One is with Eachin, where you get the elements of the array.
The other is to access the element by its index.
I prefer number two, if it is getting more complex, because there you are dealing with the elements of the array itself and not with copies of them.

Strict

Function Main:Int()
	Local map:String[][] =[["aa", "ab", "ac"],["ba", "bb", "bc"],["ca", "cb", "cc"]]
	
	Print "First version: "
	For Local i:String[] = EachIn map
		For Local j:String = EachIn i
			Print j
		End
	End
	
	Print ""
	Print "Second version: "
	For Local i:Int = 0 Until map.Length()
		For Local j:Int = 0 Until map[i].Length()
			Print map[i][j]
		End
	End

	Return 0
End



Gerry Quinn(Posted 2017) [#5]
Just to note: Monkey's array method is not unusual nowadays - it is pretty much the same as Java, for example. If anything I would say that the 'flat' C-style arrays are less common nowadays.


dubbsta(Posted 2017) [#6]
second one is the winner for me seems easier to understand and works fine, thanks phil7


dubbsta(Posted 2017) [#7]
speaking of java i think im gonna dive into other languages java/javascript at least for learning, so many tutorials out there i should pick up some new tricks. to much grinding to learn here right now


Gerry Quinn(Posted 2017) [#8]
The more languages you learn, the easier new ones come! Java is actually quite a lot like Monkey in many ways, the differences are more in the syntax (Basic-like for Monkey, C-like for java) than in the structure (Objects, methods and such-like are very similar).