Scripting Helpers is winding down operations and is now read-only. More info→
Ad
Log in to vote
0

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

Asked by 7 years ago
Edited 7 years ago

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:)

01function findSmoke(character)
02    for _, v in pairs(character:GetChildren()) do
03        if v:IsA('Part') and v.Name == 'SmokePart' then
04            return v
05        end
06    end
07end
08 
09function NPC_Module.Smoke(humanoid, character)
10    local smoke = findSmoke(character)
11    if humanoid.Health < 40 then
12        smoke.ParticleEmitter.Enabled = true
13    elseif humanoid.Health >= 40 then
14        smoke.ParticleEmitter.Enabled = false
15    end
16end

1 answer

Log in to vote
1
Answered by
Mineloxer 187
7 years ago

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.

01function findSmoke(character)
02    local smokes = {}
03    for _, v in pairs(character:GetChildren()) do
04        if v:IsA('Part') and v.Name == 'SmokePart' then
05            table.insert(smokes, v)
06        end
07    end
08    return smokes
09end
10 
11function NPC_Module.Smoke(humanoid, character)
12    local allSmoke = findSmoke(character)
13    if humanoid.Health < 40 then
14        for i, smoke in pairs(allSmoke) do
15            smoke.ParticleEmitter.Enabled = true
View all 22 lines...

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

Ad

Answer this question