开发者

In Lua, how do I remove a table within a table?

For example:

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

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


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜