Scripting Helpers is winding down operations and is now read-only. More info→
Ad
Log in to vote
1

How to clear all values in a table?

Asked by
Shawnyg 4330 Trusted Badge of Merit Snack Break Moderation Voter Community Moderator
9 years ago

Hey all! So, I'm just wondering if there's a simple way of clearing the values of a table. I believe you can use a for loop to go through each value, and remove it, but is there a simpler way? Any advice? Thanks!

2 answers

Log in to vote
3
Answered by
BlueTaslem 18071 Moderation Voter Administrator Community Moderator Super Administrator
9 years ago

If you just need to replace a table with an empty one, you can simply do that:

local a = {1, 2, 3}
print(#a) -- 3
a = {}
print(#a) -- 0

However, this won't always be what you want:

local a = {1, 2, 3}
local b = a
print(#b) -- 3
a = {}
print(#b) -- 3 (still)

In general, you should avoid doing this sort of thing -- saving references to things you take in is bad because it can be confusing (like in the above).

You have no choice but to change the actual value, which you need to do with a loop. Luckily, it's not hard at all to remove all of the values from a table:

for index in pairs(tab)
    tab[index] = nil
end
Ad
Log in to vote
2
Answered by 9 years ago
local table = {1, 2346, 6236246, "stuff", true}
table = {}

You can just overwrite the table with a blank table :)

0
Wow lol. I feel so dumb how I didn't realize that. Thanks xD! Shawnyg 4330 — 9y
0
Actually, I think Blue should've gotten the accept thing, He had multiple ways of doing it and he said there is a slight problem with doing "table = {}". EzraNehemiah_TF2 3552 — 9y

Answer this question