charozoid
charozoid

Reputation: 61

Turning a 2d array from top down to left right

So I made a script to create a 8*4 2d array which worked great but I can't figure out a way to make it from left to right instead of top to bottom. Here's what I mean :

Currently :

enter image description here

What I want is that the numbers go from left to right instead of up to down. The numbers are represented by u in my code.

for i=0,7 do
  for j=0,3 do
      local u = i*4+j+1
  end
end

Upvotes: 0

Views: 328

Answers (1)

GoojajiGreg
GoojajiGreg

Reputation: 1183

Just rearrange your loops slightly:

for i = 0, 3 do                       
    for j = 0, 7 do
         local u = i * 8 + j + 1
         print( i + 1, j + 1, u )  -- for debugging
         -- use value of u in grid square at row (i + 1 ) and column (j + 1 )
    end
end

This will output:

1   1   1
1   2   2
...
1   8   8
2   1   9
2   2   10
...
4   8   32

In other words, the values for the top row are produced first, left to right. Next the second row, and so on. Hope that helps.

Upvotes: 1

Related Questions