Removing contents of a temporary table

Sometimes the table will have content (which I need to remove) and sometimes it won’t. So would putting temp = {} reset the table to have no content? or should I use table.remove(temp) and then possibly make a new global table with the same name (temp = {}).

Thanks!

Assigning, that is doing

temp = {}

will overwrite temp with a NEW table. This might be what you want if you only do lookups through this table. However, if the table gets shared among multiple variables, like so:

local ListOfTables = {} -- Awesome function to keep a list of tables function RegisterTable (name, t) ListOfTables[name] = t end RegisterTable("temp", temp) print(ListOfTables.temp == temp) -- so, far the same table... temp = {} print(ListOfTables.temp == temp) -- will not be the same!

This is a bit contrived, but it shows that it isn’t too hard to break “identity” between two variables that began with the same table. Something to be aware of, at least.

If that is a concern, maybe this is what you want:

for k in pairs(temp) do -- we don't care about the value; obviously, we're throwing it away! temp[k] = nil end

Also, probably not a good idea to have temp global, with such a generic name.  :slight_smile:

Awesome, thanks for the explanation!

Assigning, that is doing

temp = {}

will overwrite temp with a NEW table. This might be what you want if you only do lookups through this table. However, if the table gets shared among multiple variables, like so:

local ListOfTables = {} -- Awesome function to keep a list of tables function RegisterTable (name, t) ListOfTables[name] = t end RegisterTable("temp", temp) print(ListOfTables.temp == temp) -- so, far the same table... temp = {} print(ListOfTables.temp == temp) -- will not be the same!

This is a bit contrived, but it shows that it isn’t too hard to break “identity” between two variables that began with the same table. Something to be aware of, at least.

If that is a concern, maybe this is what you want:

for k in pairs(temp) do -- we don't care about the value; obviously, we're throwing it away! temp[k] = nil end

Also, probably not a good idea to have temp global, with such a generic name.  :slight_smile:

Awesome, thanks for the explanation!