如何删除Lua表中的所有元素?
如何删除Lua表中的所有元素?我不想这样做:
t = {}
table.insert(t, 1)
t = {} -- this assigns a new pointer to t
我想保留指向 t 的相同指针,但删除 t
内的所有元素。
我尝试过:
t = {}
table.insert(t, 1)
for i,v in ipairs(t) do table.remove(t, i) end
以上有效吗?或者还需要其他东西吗?
How do I delete all elements inside a Lua table? I don't want to do:
t = {}
table.insert(t, 1)
t = {} -- this assigns a new pointer to t
I want to retain the same pointer to t, but delete all elements within t
.
I tried:
t = {}
table.insert(t, 1)
for i,v in ipairs(t) do table.remove(t, i) end
Is the above valid? Or is something else needed?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
也可以工作 - 如果表始终不用作数组,您可能会遇到 ipairs 困难。
Will also work - you may have difficulty with ipairs if the table isn't used as an array throughout.
表元素插入和删除
性能比较 表
大小计数 10000000
[1] while 和 rawset
花费的时间 = 0.677220
[2] next 和 rawset
花费的时间 = 0.344533
[3] ipairs 和 rawset
花费的时间 = 0.012450
[4] for, rawset
花费的时间 = 0.009308
表 elemnets 插入
[1]表插入函数
花费时间=1.0590489
[2]使用#t
花费时间=0.703731
[3]for,rawset
花费时间=0.100010
结果。
Table elements insert and remove
performance compare
The Table size count 10000000
[1] while and rawset
spent time = 0.677220
[2] next and rawset
spent time = 0.344533
[3] ipairs and rawset
spent time = 0.012450
[4] for, rawset
spent time = 0.009308
Table elemnets insert
[1] table insert function
spent time = 1.0590489
[2] use #t
spent time = 0.703731
[3] for, rawset
spent time = 0.100010
result.
最简单和最高效:
您的建议不可用:
table.remove
移动剩余元素以关闭漏洞,从而扰乱表遍历。有关详细信息,请参阅下一个函数的说明easiest and most performant:
What you suggest isn't usable:
table.remove
shifts the remaining elements to close the hole, and thus messes up the table traversal. See the description for the next function for more info对于忽略
__pairs
元方法的更快版本:编辑:正如 @siffiejoe 在评论中提到的,可以通过将
pairs
调用替换为它的值,将其简化回 for 循环。表的默认返回值:next
方法和表本身。此外,为了避免所有元方法,请使用rawset
方法进行表索引分配:For a faster version that ignores the
__pairs
metamethod:EDIT: As @siffiejoe mentions in the comments, this can be simplified back into a for loop by replacing the
pairs
call with its default return value for tables: thenext
method and the table itself. Additionally, to avoid all metamethods, use therawset
method for table index assignment:#table
是表格大小,因此如果t = {1,2,3}
则#t = 3
所以您可以使用此代码删除元素
while #t ~= 0 do rawset(t, #t, nil) end
您将遍历表并删除每个元素,最后得到一个空表。
#table
is the table size and so ift = {1,2,3}
then#t = 3
So you can use this code to remove the elements
while #t ~= 0 do rawset(t, #t, nil) end
You will go through the table and remove each element and you get an empty table in the end.
将变量更改为其他内容,然后返回到表,因此它是空的。
Change the variable to anything else and then back to a table, so then it is empty.