lua小技巧(一)——lua支持在遍历表的过程中删除表中字段

本文介绍在Lua中如何遍历一个表并安全地删除表中的元素,避免了传统方法中重新分配内存的问题。文章详细解释了使用pairs和next函数遍历表的过程,并强调了在遍历过程中修改现有字段或删除现有字段的安全性。
部署运行你感兴趣的模型镜像

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的遍历顺序是未知的,然而,你可以在遍历时修改已有的字段,或者,你可以删除已经存在的字段。

您可能感兴趣的与本文相关的镜像

Wan2.2-T2V-A5B

Wan2.2-T2V-A5B

文生视频
Wan2.2

Wan2.2是由通义万相开源高效文本到视频生成模型,是有​50亿参数的轻量级视频生成模型,专为快速内容创作优化。支持480P视频生成,具备优秀的时序连贯性和运动推理能力

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值