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

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

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值