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

Help with loops?

This script makes a weld for the left arm but not for the right arm,why and how do I fix this problem?

Please explain how you manged to fix it.

Player = game.Players.LocalPlayer
Character = Player.Character
Torso = Character.Torso
Mouse = Player:GetMouse()
----------------------------------------
function CharacterCheck()
	if not Character or Character.Parent == nil then
	Character = Player.CharacterAdded:wait()
	end
end
CharacterCheck()
----------------------------------------
function MakeWelds()
	local Arms = {Character["Left Arm"],
				  Character["Right Arm"]
	}
	local ArmWelds = {}
	for i,v in pairs (Arms) do
		local Weld = Instance.new("Weld",Torso)
		Weld.Name = v.Name.." Weld"
		Weld.Part0 = v
		Weld.Part1 = Torso
		ArmWelds[i] = Weld
		return ArmWelds
	end
end
Welds = MakeWelds()
for i,v in pairs (Welds)do
	print(v)
end
----------------------------------------
	LeftClick = Mouse.Button1Down:connect(function()
		print("LeftClick")
	end)
	

1 answer

✓ Accepted answer

Using return in a function stops the function. You're using return before the for loop has ended so it will only create the one weld before returning the ArmWelds table.

To remedy this, switch line 24 and 25 so that the end on line 25 is before the return. Now the for loop will run and create both welds before returning the ArmWelds table, see below:

Player = game.Players.LocalPlayer
Character = Player.Character
Torso = Character.Torso
Mouse = Player:GetMouse()
----------------------------------------
function CharacterCheck()
	if not Character or Character.Parent == nil then
		Character = Player.CharacterAdded:wait()
	end
end
CharacterCheck()
----------------------------------------
function MakeWelds()
	local Arms = {Character["Left Arm"],
		Character["Right Arm"]
	}
	local ArmWelds = {}
	for i,v in pairs (Arms) do
		local Weld = Instance.new("Weld",Torso)
		Weld.Name = v.Name.." Weld"
		Weld.Part0 = v
		Weld.Part1 = Torso
		ArmWelds[i] = Weld
	end --The end is switched so that the for loop can run for how long it needs to, before moving onto the next line.
	return ArmWelds --Return the ArmWelds table after all parts have been looped through in the Arms table.
end

Welds = MakeWelds()
for i,v in pairs (Welds)do
	print(v)
end
----------------------------------------
LeftClick = Mouse.Button1Down:connect(function()
	print("LeftClick")
end)

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