Accessing a multi-dimensional array?

Questions about the LÖVE API, installing LÖVE and other support related questions go here.
Forum rules
Before you make a thread asking for help, read this.
Post Reply
FoundationIDE
Prole
Posts: 6
Joined: Wed Jun 05, 2013 6:51 pm

Accessing a multi-dimensional array?

Post 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.
User avatar
Plu
Inner party member
Posts: 722
Joined: Fri Mar 15, 2013 9:36 pm

Re: Accessing a multi-dimensional array?

Post 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.
User avatar
micha
Inner party member
Posts: 1083
Joined: Wed Sep 26, 2012 5:13 pm

Re: Accessing a multi-dimensional array?

Post 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.
Post Reply

Who is online

Users browsing this forum: No registered users and 5 guests