2D arrays

Hi, I’m a noob at Corona but have programmed in C++ before. In C++ it is really easy to make 2D arrays, but when I tried the same method in Corona, it didn’t work. I was wondering if 2D arrays exist in Corona, and if they do, how you create and index one.
Thanks,

PS. so far I have tried this method

local grid = {3,3} grid[1,1] = display.newText( "Hello World", 0,0) [import]uid: 74478 topic_id: 16245 reply_id: 316245[/import]

try grid[1][1] instead

however

local grid = {3,3} 

is essentially not a 2D array, but the same as

grid[1] = 3  
grid[2] = 3  
local grid = {  
 {1,2,3,4}, --\> this is grid[1]  
 {5,6,7,8} --\> this is grid[2]  
}  
  
print(grid[2][3]) ===\> 7  

cheers,

?:slight_smile: [import]uid: 3826 topic_id: 16245 reply_id: 60516[/import]

Here’s another quick example to help illustrate how to accomplish 2D arrays in Corona.

local map = {}local width = 10local height = 10for x=1,width do if not map[x] then map[x] = {}; end for y=1,height do map[x][y] = x .. ", " .. y endendprint( map[2][4] ) -- output: 2, 4[/code]The above creates a 10x10 matrix, such as that which would be used in a 2D tile-based game. [import]uid: 52430 topic_id: 16245 reply_id: 60522[/import]

jB,

I get what you’re doing except for the “if not” syntax.
Is it basically saying if map[x] is nil then create a vertical column?

Thanks
Dane [import]uid: 117490 topic_id: 16245 reply_id: 80723[/import]

@Dane:

The statement “if not x then” is the same as either of the two statements below:

  • if x == nil then

  • if x == false then

[import]uid: 52430 topic_id: 16245 reply_id: 80730[/import]