How to populate a grid from a one dimensional table?

I have a table:

local table = { obj1, obj2, obj3, obj4, obj5, obj6}

And I would like to convert that table into a  2 dimensional table ( a grid ):

local grid = {} local columns = 4 local rows = 4 for x=1,columns do grid[x] = {} for y=1,rows do grid[x][y] = table[??] end end

Also how to deal with the situation if the first table has fewer values than the columns/rows?

local input = { obj1, obj2, obj3, obj4, obj5, obj6} local columns = 4 local rows = 4 local function doConvertTo2D( input, cols, rows ) local grid = {} local index = 1 for x=1,columns do grid[x] = {} for y=1,rows do grid[x][y] = input[index] index = index + 1 if (index \> #input) then return end end end return grid end doConvertTo2D( input, cols, rows )

if you just index table[(y-1)*columns+x] you’ll automatically get nils if not enough values

(btw, using “table” as a variable name, while legal, is discouraged)

real question is, assuming this represents real code and not just dummy/demo, why not just just define it as 2D to begin with?

Can you give me a sample code?

 Thanks, appreciate it.

local grid = { { obj1, obj2, obj3, obj4 }, { obj5, obj6, nil, nil }, { nil, nil, nil, nil }, { nil, nil, nil, nil } } -- and done, that's all you need. -- (you could even eliminate some of those verbose nils which do nothing, i just left them in to show 4x4 structure)

The problem with that approach is that I’m populating the grid dynamically. The user adds/removes objects to a table and each time, I redraw the grid based on the new data. That’s why I went with a 1 dimensional table.

then answer already given, just plug it into your original code.

local input = { obj1, obj2, obj3, obj4, obj5, obj6} local columns = 4 local rows = 4 local function doConvertTo2D( input, cols, rows ) local grid = {} local index = 1 for x=1,columns do grid[x] = {} for y=1,rows do grid[x][y] = input[index] index = index + 1 if (index \> #input) then return end end end return grid end doConvertTo2D( input, cols, rows )

if you just index table[(y-1)*columns+x] you’ll automatically get nils if not enough values

(btw, using “table” as a variable name, while legal, is discouraged)

real question is, assuming this represents real code and not just dummy/demo, why not just just define it as 2D to begin with?

Can you give me a sample code?

 Thanks, appreciate it.

local grid = { { obj1, obj2, obj3, obj4 }, { obj5, obj6, nil, nil }, { nil, nil, nil, nil }, { nil, nil, nil, nil } } -- and done, that's all you need. -- (you could even eliminate some of those verbose nils which do nothing, i just left them in to show 4x4 structure)

The problem with that approach is that I’m populating the grid dynamically. The user adds/removes objects to a table and each time, I redraw the grid based on the new data. That’s why I went with a 1 dimensional table.

then answer already given, just plug it into your original code.