如何在删除密钥时安全地迭代 lua 表 [英] How can I safely iterate a lua table while keys are being removed

查看:20
本文介绍了如何在删除密钥时安全地迭代 lua 表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的主协程中,我根据用户操作从表中删除或添加条目.在后台,我想遍历表中的条目.如果我在一次迭代中错过了插入,我并不介意,前提是我可以在下一次之前抓住它.

In my main coroutine, I am removing or adding entries from a table depending on user operations. In the background, I'd like to iterate over the entries in the table. I don't mind particularly if I miss an insertion on one iteration, providing I can catch it before the next.

使用 pairs 迭代它是否安全?还是我应该使用 next 代替?

Is it safe to iterate over it with pairs? Or should I use next instead?

推荐答案

您可以在遍历表时安全地删除条目,但不能创建新条目,即新键.不过,您可以修改现有条目的值.(删除条目是该规则的一个特例.)

You can safely remove entries while traversing a table but you cannot create new entries, that is, new keys. You can modify the values of existing entries, though. (Removing an entry being a special case of that rule.)

这篇关于如何在删除密钥时安全地迭代 lua 表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆