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?

1

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

Comments

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

3 Comments

Is it possible to use named keys in this type of setup instead of numeric row/column indexing? How would I do that?
@MaxWell, yes, just adjust the loops accordingly. Please ask a separate question with examples of what you're trying to achieve.
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. stackoverflow.com/questions/73587448/…

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.