在Lua中,如何删除表中的表?

发布于 2024-08-13 02:21:35 字数 271 浏览 4 评论 0原文

例如:

items = {
    [753] = {
    },
    [192] = {
    },
    [789] = {
    },
    [791] = {
    },
    [790] = {
    },
    [776] = {
    },
}

我想删除789和其中的所有数据。我都尝试过: 表. 删除( 项目, 2 );和 table.remove( items, 789 ); (我不确定索引是如何工作的)但运气不好。

For example:

items = {
    [753] = {
    },
    [192] = {
    },
    [789] = {
    },
    [791] = {
    },
    [790] = {
    },
    [776] = {
    },
}

I would like to remove 789 and all data inside of it. I tried both:
table.remove( items, 2 ); and table.remove( items, 789 ); ( I wasn't sure how the indexing worked ) with no luck.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

月下伊人醉 2024-08-20 02:21:35

就像

items[789] = nil

在 Lua 中一样简单,如果表中的某个键具有 nil 值,那么就好像该键不存在一样。

> t = { [5] = {}, [10] = {} }
> for k,v in pairs(t) do print(k,v) end
5       table: 0037CBC0
10      table: 0037CBE8
> t[5] = nil
> for k,v in pairs(t) do print(k,v) end
10      table: 0037CBE8

另请参阅Lua 编程,第 2.5 节。 (尽管在线版本是为Lua 5.0编写的,但这仍然适用于Lua 5.1)

...您可以将 nil 分配给表字段以将其删除。

当您将 nil 分配给索引时,这不会显式删除以前存储在该索引中的内容;而是会删除该索引中以前存储的内容。但它确实降低了存储在那里的引用计数,可能使其符合垃圾回收的条件。

It's as easy as

items[789] = nil

In Lua, if a key in a table has a nil value, then it's as though the key does not exist.

> t = { [5] = {}, [10] = {} }
> for k,v in pairs(t) do print(k,v) end
5       table: 0037CBC0
10      table: 0037CBE8
> t[5] = nil
> for k,v in pairs(t) do print(k,v) end
10      table: 0037CBE8

See also Progamming in Lua, section 2.5. (Even though the online version is written for Lua 5.0, this still applies to Lua 5.1)

... you can assign nil to a table field to delete it.

When you assign nil to your index, that doesn't explicitly delete what was previously stored in that index; but it does lower the reference count for what was stored there, potentially making it eligible for garbage collection.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文