Question

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.

Was it helpful?

Solution

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top