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

Why my function return just one part? (for _, v in pairs() do)

So, I want that "findSmoke" find all part named "SmokePart" and return all it to NPC_Module.Smoke but this return juste one part, why and how to correctly fix this? Thank for answers and the explanations:)

function findSmoke(character)
	for _, v in pairs(character:GetChildren()) do
		if v:IsA('Part') and v.Name == 'SmokePart' then
			return v
		end
	end
end
	
function NPC_Module.Smoke(humanoid, character)
	local smoke = findSmoke(character)
	if humanoid.Health < 40 then
		smoke.ParticleEmitter.Enabled = true
	elseif humanoid.Health >= 40 then
		smoke.ParticleEmitter.Enabled = false
	end
end

1 answer

✓ Accepted answer

In this case, return statements end the function by returning a value. Instead of returning the first smoke it finds, try adding it to a table. Then after the loop has finished, return the table.

function findSmoke(character)
    local smokes = {}
    for _, v in pairs(character:GetChildren()) do
        if v:IsA('Part') and v.Name == 'SmokePart' then
            table.insert(smokes, v)
        end
    end
    return smokes
end

function NPC_Module.Smoke(humanoid, character)
    local allSmoke = findSmoke(character)
    if humanoid.Health < 40 then
        for i, smoke in pairs(allSmoke) do
            smoke.ParticleEmitter.Enabled = true
        end
    elseif humanoid.Health >= 40 then
        for i, smoke in pairs(allSmoke) do
            smoke.ParticleEmitter.Enabled = false
        end
    end
end

I didn't test this for bugs, but this should work.

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