lua-users home
lua-l archive

[Date Prev][Date Next][Thread Prev][Thread Next] [Date Index] [Thread Index]

My apologies if this has been answered, couldn't see a specific reference to it.

I want to delete all elements from a table (any sort of keys, not just numeric).

However I don't want to just to do this:

t = {}  -- make fresh, empty table

The reason for that is some of my sub-modules may have stored the reference to the table in a local variable, creating a new table won't empty those out. The original table needs to have its entries removed.

Is this OK?

t = { a = 1, b = 2, c = 3, 4 = 4}

for k in pairs (t) do
  t [k] = nil
end -- for

It *seems* to work however I seem to recall that you aren't supposed to change keys during a table traversal (like, doing a "tostring" on them). However does deleting a key count as changing it?

Or, do I need to create a second table with all the keys in it, and traverse the second table, deleting elements from the first table, and then remove the second table? Sounds like a messier way of doing it.

- Nick