Lua:向表中添加多行 [英] Lua: Adding multiple rows to tables
问题描述
好,所以我希望快速生成一个很大的表.看起来像这样:
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},
}
只有表将包含更多的行,并且这些行中的值也更多.我知道使用table.insert()可以轻松地在一行中添加任何我需要的内容,但是无论如何我也可以在不键入全部内容的情况下添加整个新行?
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?
推荐答案
使用for
循环.
t = { }
for i = 1,100 do
table.insert(t, i) -- insert numbers from 1 to 100 into t
end
二维数组也非常简单
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
您可能还记得local current_row = t[row]
中的当前行,但是在进行概要分析之前,请勿尝试使用这些方法来提高性能!如果您认为更清楚地表达了目的,则仅将它们用于可读性.
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.
还要注意(在5.1及更高版本中,#
尤其时髦),您可以直接将值分配给不存在的索引,然后将它们添加.
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.
这篇关于Lua:向表中添加多行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!