Its because you are iterating through the table as you are attempting to clear it. The contents of the table shift down, and the shifting causes a few items to remain.
Just setting the table to {} should suffice if you are just looking to clear it entirely.
table.remove()'s second parameter must be the index of the value you’re trying to remove. You can’t pass it the value and expect it to clean it.
local Table = {5, 3, 8, 1, 4}
for i, v in Table do
table.remove(Table, i) -- The "i" here is the index of the value, for example for the index "1", the value would be "5".
end
print(Table) -- Should print "{}"
there’s a hack in programming where you can go through values in reverse, so the next indexes will remain unchanged
local Table = {5, 3, 8, 1, 4}
print(Table) -- {5, 3, 8, 1, 4}
for i = #Table, 1, -1 do
local v = Table[i]
if v % 2 == 0 then -- every even number
table.remove(Table, i)
end
end
print(Table) -- {5, 3, 1}
You are using table.remove incorrectly, that’s why! It expects a list, and a list index, not a value in a list. The correct code would be this:
local Table = {5, 3, 8, 1, 4}
for i, v in Table do
table.remove(Table, table.find(Table, v))
end
task.wait(4)
print(table.concat(Table, " "))
It seems you are using a for loop to clear a list. Why not use table.clear()? If you had other code that did something else per each item, that would make sense.
Sidenote
Here’s why your code prints {3, 1}.
local Table = {5, 3, 8, 1, 4}
for i, v in Table do
table.remove(Table, table.find(Table, v))
end
This is going to remove index 5, then 3, then 8, etc. Here’s what the list looks like after each interation:
{(5), 3, 8, 1, 4} -- remove [5]
{5, (3), 8, 1} -- remove [3]
{5, 3, (1)} -- remove [1]
{3, 1, (nil)} -- end loop (no other item in list)
{3, 1} -- result
Just to clarify on your final part explaining the iteration of his original loop, I believe you may have made a small error. I’ve updated it so it may be a bit more clear.
{(5), 3, 8, 1, 4} -- remove 1st index: [5], table shifts to the left after the removed value
{3, (8), 1, 4} -- remove 2nd index: [8], table shifts to the left after the removed value
{3, 1, (4)} -- remove 3rd index: [4], table shifts to the left after the removed value
{3, 1, nil, (nil)} -- end loop (no other item in list)
{3, 1} -- result
Edit: I’ve misread, sorry! You were right, I incorrectly considered a:
for i, v in Table do
table.remove(Table, i) -- i instead of v
end