Scripting HelpersARCHIVE
A little piece of Roblox history. Preserved for everyone, one question at a time.Read about the archive →
COMMUNITY QUESTION

[SOLVED] Why is my script not properly removing items from a table?

I have the following server script, where character is equivilant to game.Players.LocalPlayer.Character:

local current_accessories = character:GetChildren()
local position = 1
for _,i in pairs(current_accessories) do
    if i.ClassName == "Hat" then
        i.Destroy()
        table.remove(current_accessories,position)
        print("Went through if: "..i)
    elseif i.ClassName == "Accessory" then
        print("Went through elseif: "..i)
    else
        print("Went through else: "..i.Name)
        table.remove(current_accessories,position)
    end
    position += 1
end
print(current_accessories)

After running it, it hasn't removed all of the instances other than accessories from the table. Thus when print(current_accessories) is called at the end, it returns [1] = RightLowerArm, [2] = Pants, [3] = Head, [4] = Animate, [5] = RightFoot, [6] = RightUpperLeg, [7] = LeftLowerLeg, [8] = UpperTorso, [9] = LeftUpperArm, [10] = LeftHand, [11] = Shirt, [12] = Tech Noir Helm, [13] = Finalized Wings v2, [14] = CrypticSword

However, according to the output, all the non-accessory items did in fact go through the

else
    print(i)
    table.remove(current_accessories,position)

function. This leads me to believe that something is wrong with how I am using table.Remove(), but I can't figure it out. Any help would be appreciated.

2 answers

I'm not exactly sure what you're trying to accomplish, but according to the Roblox wiki, Instance.ClassName is not replicated from the server to the client, meaning it isn't available to LocalScripts. Try using the IsA function to check the type of the accessories

https://developer.roblox.com/en-us/api-reference/property/Instance/ClassName https://developer.roblox.com/en-us/api-reference/function/Instance/IsA

3 comments

0

The script is actually a server script in ServerScriptService, but the character value is equivilent to LocalPlayer.Character. Also it detects fine that it isnt an accessory, it just doesnt remove it from the list.

0

I'll try IsA tho, and see if it works

0

Update: Still didn't work. The problem isnt with the detection, its that the items arent being removed from the table

Solved. Apparently table.remove() doesn't work properly when iterating. Script that works:

local current_accessories = {}

for _, child in ipairs(character:GetChildren()) do
	if child:IsA("Accessory") then
		table.insert(current_accessories, child)
	end
end
print(current_accessories)

This discussion is preserved as it was. New answers, comments, and votes are closed.