Page 1 of 1

Accessing a multi-dimensional array?

Posted: Wed Jun 05, 2013 8:51 pm
by FoundationIDE

Code: Select all

sample_map = {
	{1,0,0,0,0,0,0,0},
	{0,0,0,0,0,0,0,0},
	{0,0,0,0,0,0,0,0},
	{0,0,0,0,0,0,0,0},
	{0,0,0,0,0,0,0,0},
	{0,0,0,0,0,0,0,0},
}
This is an array which I plan to populate data for my level. I am just wondering, is there a function to access a column on a specific row?

for example, I was thinking:

Code: Select all

function love.draw()
      col = GetLevelData_Column(1) --Column 1
      row = GetLevelData_Row(1) --Row 1
end

function GetLevelData_Column(column)
     ...
     return Get Column 'column'
     ...
end

function GetLevelData_Row(row)
     ...
     return Get row 'row'
end

just wondering if such a function exists or how would i approach it?
Thanks.

Re: Accessing a multi-dimensional array?

Posted: Wed Jun 05, 2013 9:11 pm
by Plu
You can simply access them directly using the table notation.

Code: Select all

sample = { 6, 7, 8, 9, 10 }
sample[1] -- this will yield 6
sample[3] -- this will yield 8

Code: Select all

sample = { { 6, 7, 8}, {9, 10, 11} }
sample[1][1] -- this will yield 6
sample[2][3] -- this will yield 11
sample[1] -- this will yield { 6, 7, 8 }, the whole row

Sidenote when using a multidimensional array:

Code: Select all

sample[1][6] -- this will yield NIL
sample[6][1] -- this will crash your game! 
If the last key can't be found, you get nil. If an earlier key can't be found, the game will crash with a "trying to access a nil-value" message.

Re: Accessing a multi-dimensional array?

Posted: Thu Jun 06, 2013 5:47 am
by micha
There is no explicit function for accessing columns. My two suggestions: Either write a function that return a column like getColumns(matrix, columnNumber) or transpose the matrix and then get a row. Depending on the actual content of your project you can maybe work with the transposed matrix all the time and never need to get a column?

And last, don't forget that each row in such a 2d-array can have a different length. So you either have to check, if the array has a rectangular shape, or you have to guarantee it in your code, by only constructing rectangular shaped arrays.