Removing a value from a table

I am modifying a datastore which is a table. What I want is to understand what happens if I modify that table multiple times. For example, if I had a table like this

local Table = {"a","b","c"}

and then removed it doing this

table.remove(Table,1)

all the values would shift back one, right? So if I then did

table.remove(Table,2)

it would remove A and C instead of A and B right?

I am then wondering, if I set the value to nil instead, I saw in a different thread that then the table would go like this

Table[1] = nil
output(t2) -- 1 = a, 3 = c

But if this is the case, does that mean that the table is still 3 sets long?
How would I go about removing specific indices, to make the table less long, and still remove the correct indices without the table shifting and the wrong ones moving

2 Likes

table.remove(Table, table.find(Table, "b"))

1 Like

What weakroblox said would be the right way to go about it but I just want to answer your questions:

Yes, the indices are shifted over as soon as the table.remove call is finished.

No, in this case if you try using the length operator (#) on it you will get 1 because of the missing index (without a custom __len metamethod, this operation will return any number and stop at the missing index - 1). It won’t shift anything over either which is why you would use table.remove here. If you attempt to iterate over it using ipairs it will also stop iterating after ‘a’.

Going off on a tangent here but generalized iteration or using pairs solves the stopping at the missing index part, but it’s always faster to iterate over a table with no missing numerical indices than it is to iterate over a table with missing or non-numerical indices.

1 Like

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.