Table.remove not removing an element

I want to remove an element from a table

table.remove does not throw an error, but also does not remove the specified element
Element 5 should be gone: (but it is not)
(this is printed after the table.remove code runs)

image

Code:

--[[
Assume targetSlot has a value of 5 (I checked dont worry)
Data = {
["1"] = {},
["2"] = {},
["3"] = {},
["4"] = {},
["5"] = {},
["auto_save"] = {}
}
]]

-- removing data
table.remove(data, tostring(targetSlot))
					
print("Updated data:", data)

-- updating player data
dataStore:SetAsync(player.UserId, data) 

This is because table.remove() only accepts a number.
Try this:

table.remove(data, table.find(data, tostring(targetSlot)))
3 Likes

Okay this might work, going to try now

Element 5 is still there (did not work)
image

Code:

-- removing data
table.remove(data, table.find(data, tostring(targetSlot)))

table.remove only removes elements from arrays, which have numbered keys. Your keys are strings, so table.remove will not work.

Either change your keys to numbers or set the key to nil by doing t["5"] = nil or t[tostring(targetSlot)] = nil.

1 Like

But what if I want to remove the key entirely?

Have you tried it? Setting the value of a key to nil will remove it completely.

You wrote data with a small letter, that’s the error.

Also I noticed that it removes the element at a index, so it should work… I think

There is no error?

extra charactersextra charactersextra charactersextra charactersextra charactersextra charactersextra characters

data = {
[“1”] = {},
[“2”] = {},
[“3”] = {},
[“4”] = {},
[“5”] = {},
[“auto_save”] = {}
}
]]

– removing data
table.remove(data, table.find(data, tostring(targetSlot)))

print(“Updated data:”, data)

– updating player data
dataStore:SetAsync(player.UserId, data)

What is wrong with just doing data[key] = nil?

What about that?

extra charactersextra charactersextra charactersextra charactersextra charactersextra characters

I want to remove the element completely, wait I was thinking of
data[key] = {} to remove the data
hold on let me test
data[key] = nil

OP could have mistyped the variable name in the post.

1 Like

Setting it to nil will completely remove it, that’s one of the features of Lua. Setting it to an empty table seems like a reasonable alternative too if you want to preserve the keys

Okay yeah
data[key] = nil
worked
idk why I was thinking of
data[key] = {}
when I saw
data[key] = nil

Thanks everyone!

1 Like

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