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

CheckForTool function always returns false..?

Asked by 7 years ago

I wanted to call a function to see if there was a tool in the character. However, the function returns false even though I checked and the tool was in the character.

function checkforTool()
    for _,tool in ipairs(plr.Character:GetChildren()) do
        if tool:IsA("Tool") then
            return true
        else
            return false
        end
    end
end

Don't worry about missing variables, I'm just trying to get to the point. Am I using the for loop correctly?

0
You could just return tool:IsA("Tool") by the way. Link150 1355 — 7y

1 answer

Log in to vote
2
Answered by
M39a9am3R 3210 Moderation Voter Community Moderator
7 years ago

Problem

What is happening is, whenever that first object of Character is found out not to be a tool, the function will automatically return the false value.


Solution

Wait to return the false value at the end of the loop. That way you've gone through all objects and there are no tools detected.


Final Script

function checkforTool()
    for _,tool in ipairs(plr.Character:GetChildren()) do
        if tool:IsA("Tool") then
            return true
        end
    end
    return false --All you had to do was move return false to outside the for loop.
end

Hopefully this answered your question. If it did, do not forget to hit the accept answer button. If you have any questions, feel free to comment below and I will get back to you.
Ad

Answer this question