Lua: Adding multiple rows to tables

可紊 提交于 2019-12-10 15:37:48

问题


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:


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.




回答2:


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


来源:https://stackoverflow.com/questions/15085204/lua-adding-multiple-rows-to-tables

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!