Does "table = {}" clear a table?

If I were to keep the players in a game within a table that is refreshed each game loop iteration, could I clear that table by simply using the line “table = {}”? Or would that just add nothing to table and keep the current values.

1 Like

Yes it would have the behavior of clearing the table, but beware what it actually does is create a new one in the process and assign it to your variable.

local a = {1, 2, 3}
a = {3, 2, 1} -- these are 2 different tables!

local b = {0, 2, 4}
print(b == {0, 2, 4}) -- false, {} creates a new table

As long as you’re not relying on any weird behavior/comparison, and updating your references to the table after you use var = {}, you will be fine and it will essentially “clear” the table.

9 Likes

Sounds good, thank you! The player table becomes useless outside of that one round of the game, so creating a new one works perfectly. Thanks for the quick response.

What do you mean by “updating your references to the table”? Kinda curious since I want to make sure that if I ever wanted to use this method I’d know how to do it correctly.

1 Like
local a = {3, 2, 1}
local b = a

In this example, both a and b are references to the same table; they are 2 variables pointing to the same object.

As such,

a[1] = 0
print(b[1]) --> 0

This is because we’re accessing the object there with []. However, if you did…

a = {}
print(b[1]) --> 0

You still get 0 because you only updated what the variable a refers to, but b is still pointing to the same old table. Because of this, if you refer to a table in multiple places and forget to update the references (for example by doing b = a again) you may end up in a situation where what you think is the same table as another might not be, or vice versa, leading to tricky code bugs.

6 Likes

Thanks for the clear clarification and examples. Definitely something I’ll keep an eye out for in my code :slight_smile: