tags:

views:

110

answers:

1

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.

Thanks.

+3  A: 

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.

Mark Rushakoff
Wow, thanks for the help, been trying to do that a dozen different ways without luck :)
Rob
If you haven't used a garbage-collected language that uses reassignment to delete variables before, I don't think that assigning `nil` would be anyone's first guess. Anyway, you're welcome.
Mark Rushakoff