Getting players accessories (shortening code)

I have this code which gets a players accessories from their HumanoidDescription, and converts the strings to Folders (that’s what Converter.Convert() does) and this is so I can use data stores to store their current look. However, this feels really long and messy, espcecially since I’m gonna have to do this several more times for all the other accessories (shoulder, back, waist, etc)

for _, id in ipairs(humanoidDescription.HatAccessory:split(',')) do
	if id ~= '' then
		local Item = id
		
		local NewValue = Converter.Convertr(Item)
		NewValue.Name = id
	
		NewValue.Parent = PlayerData.Character['Hats']
	end
end
			
for _, id in ipairs(humanoidDescription.HairAccessory:split(',')) do
	if id ~= '' then
		local Item = id
					
		local NewValue = Converter.Convertr(Item)
		NewValue.Name = id
		
		NewValue.Parent = PlayerData.Character['Hairs']
		end
end

for _, id in ipairs(humanoidDescription.FaceAccesssory:split(',')) do
	if id ~= '' then
		local Item = id
		
		local NewValue = Converter.Convertr(Item)
		NewValue.Name = id
		
		NewValue.Parent = PlayerData.Character['Face Accesssories']
	end
end
1 Like

You should use functions so you wouldn’t need to write 8 lines of the same code code over and over again.

local function accessoryToPlayerData(id, accessoryName)
	local Item = id
		
	local NewValue = Converter.Convertr(Item)
	NewValue.Name = id
	
	NewValue.Parent = PlayerData.Character[accessoryName]
end

for _, id in ipairs(humanoidDescription.HatAccessory:split(',')) do
	if id ~= '' then
		accessoryToPlayerData(id, 'Hats')
	end
end
			
for _, id in ipairs(humanoidDescription.HairAccessory:split(',')) do
	if id ~= '' then
		accessoryToPlayerData(id, 'Hairs')
	end
end

for _, id in ipairs(humanoidDescription.FaceAccesssory:split(',')) do
	if id ~= '' then
		accessoryToPlayerData(id, 'Face Accesssories')
	end
end
1 Like