4

Ok, so I'm looking to quickly generate a rather large table. Something that would look like this:

table{
{1, 1, 1, 1},
{1, 1, 1, 1},
{1, 1, 1, 1},
}

Only the table would contain far more rows, and far more values in those rows. I know using table.insert() I can easily add however many I need to a single row, but is there anyway I can also add whole new rows without typing it all out?

brunothepig
  • 43
  • 1
  • 4

2 Answers2

5

Use a for loop.

t = { }
for i = 1,100 do
    table.insert(t, i) -- insert numbers from 1 to 100 into t
end

2D arrays are also very simple

t = { }
for row = 1,20 do
    table.insert(t, { }) -- insert new row
    for column = 1,20 do
        table.insert(t[row], "your value here")
    end
end

You could remember current row as in local current_row = t[row], but don't try these things to improve performance until you profile! Use them merely for readability, if you think it clearer expresses the purpose.

Also note that (and it's especially funky in 5.1 and newer with the #) you can just directly assing values to nonexisting indices, and they will be added.

Bartek Banachewicz
  • 38,596
  • 7
  • 91
  • 135
4

You don't need to use table.insert:

t = {}
for row = 1,20 do
    t[row] = {}
    for column = 1,20 do
        t[row][column]= "your value here"
    end
end
lhf
  • 70,581
  • 9
  • 108
  • 149
  • Is it possible to use named keys in this type of setup instead of numeric row/column indexing? How would I do that? – Max Well Sep 02 '22 at 19:06
  • @MaxWell, yes, just adjust the loops accordingly. Please ask a separate question with examples of what you're trying to achieve. – lhf Sep 02 '22 at 19:20
  • Thanks, @lhf. I finally worked out how to set it up. Now I'm struggling with how to sort it. Here's my original post on the issue. https://stackoverflow.com/questions/73587448/sort-index-of-tables-based-on-value-for-a-key-in-each-table – Max Well Sep 03 '22 at 00:09