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 6 years ago
Edited 6 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:)

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

Log in to vote
1
Answered by
Mineloxer 187
6 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.

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.

Ad

Answer this question