lua支持在遍历表的过程中删除表中字段
Ask: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
Answer:
for k in pairs (t) do
t [k] = nil
end
lua不同于c#,支持边遍历表边删除表中的字段,这点在官方文档里面也有提及:
next (table [, index])
Allows a program to traverse all fields of a table. Its first argument is a table and its second argument is an index in this table. next returns the next index of the table and its associated value. When called with nil as its second argument, next returns an initial index and its associated value. When called with the last index, or with nil in an empty table, next returns nil. If the second argument is absent, then it is interpreted as nil. In particular, you can use next(t) to check whether a table is empty.
The order in which the indices are enumerated is not specified, even for numeric indices. (To traverse a table in numeric order, use a numerical for.)
The behavior of next is undefined if, during the traversal, you assign any value to a non-existent field in the table. You may however modify existing fields. In particular, you may clear existing fields.
最后一段翻译下,当在遍历表的时候为不存在的字段赋值时,next的遍历顺序是未知的,然而,你可以在遍历时修改已有的字段,或者,你可以删除已经存在的字段。
本文介绍在Lua中如何遍历一个表并安全地删除表中的元素,避免了传统方法中重新分配内存的问题。文章详细解释了使用pairs和next函数遍历表的过程,并强调了在遍历过程中修改现有字段或删除现有字段的安全性。

被折叠的 条评论
为什么被折叠?



