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

Why isn't this loop working?

Asked by 10 years ago

I have a while true do loop that checks if something in a player's backpack exists through a LocalScript. Here's the script:

repeat wait() until game.Players.LocalPlayer.Character
local gun = game.Players.LocalPlayer.Backpack:findFirstChild("Sniper Rifle")

while true do
    wait(1)
    if not gun then
        print("gun is nil")
    else
        print("gun is not nil")
    end
end

The problem is, though, that even if the tool is removed, the output still says "gun is not nil", despite the gun not being in the player's inventory. Why is this happening?

1 answer

Log in to vote
1
Answered by
Goulstem 8144 Badge of Merit Moderation Voter Administrator Community Moderator
10 years ago

The problem here is that you're defining the gun outside the scope of the while loop. Doing this will make it check if the gun existed when it was defined, AKA when it wasn't nil to begin with.

So you have to define the gun inside the scope of the While loop for this to work.

wait(2)

local plr = game.Player.LocalPlayer
repeat wait() until plr.Character

while wait(1)
    local gun = plr.Backpack:findFirstChild("Sniper Rifle")
    if gun then
        print("gun is not nil")
    else
        print("gun is nil")
    end
end
Ad

Answer this question