سؤال

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?

هل كانت مفيدة؟

المحلول

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.

نصائح أخرى

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
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top