Passing 2D Arrays to Functions?

BlitzMax Forums/BlitzMax Programming/Passing 2D Arrays to Functions?

zoqfotpik(Posted 2014) [#1]
Is there a canonical way to pass 2D arrays to functions?

Am I better off encapsulating the array in an object and passing that? If so, that's fine and at least the object is operating on itself rather than the function doing so with side effects.


Derron(Posted 2014) [#2]
SuperStrict

Global MyArray:int[][] = [[1,2], [3,4]]

Function PassArray:Int(arr:int[][])
	For local sub:int[] = eachIn arr
		for local i:int = eachIn sub
			print i
		Next
	Next
End Function

PassArray(MyArray)


Global MyArray2:int[2,2]
MyArray2[0,0] = 1
MyArray2[0,1] = 2
MyArray2[1,0] = 3
MyArray2[1,1] = 4

Function PassArray2:Int(arr:int[,])
	For local i:int = 0 until arr.numberOfDimensions
		For local j:int = 0 until arr.length / arr.numberOfDimensions
			print i+","+j+"  "+arr[i,j]
		Next
	Next
End Function

print "----"
PassArray2(MyArray2)



bye
Ron


TomToad(Posted 2014) [#3]
SuperStrict

Local a:Int[10,10] 'create a 2 dimensional array
FillArray(a) 'call a funtion to fill the array

For Local y:Int = 0 To 9 'print the contents of the array
	Local s:String = ""
	For Local x:Int = 0 To 9
		s = s+a[x,y] + " "
	Next
	Print s
Next

Function FillArray(a:Int[,])
	Local Dimensions:Int[] = a.Dimensions() 'Dimensions[0] contains the number of elements in the first Dimension, Dimension[1] for the second
	
	'fill the array
	For Local x:Int = 0 Until Dimensions[0]
		For Local y:Int = 0 Until Dimensions[1]
			a[x,y] = x+y*Dimensions[1]
		Next
	Next
End Function



zoqfotpik(Posted 2014) [#4]
Thank you.

I'm struggling with how to structure tilemap display. Ordinarily I would have the tilemap be global and that would be that but I am doing something with multiple maps and rolling arrays that mean that I have to encapsulate it and decouple it.