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

查看:205
本文介绍了如何在删除密钥时安全地迭代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.

使用<$ c迭代它是否安全$ C>对?或者我应该使用 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天全站免登陆