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

How to make a constantly updating count of an amount of true bools???

Asked by 6 years ago

I am trying to make a script that constantly has the amount of players at a set place, but I can't get my script to work.

_G.numberOfPlayers = 0
local players = game.Players
for I, v in pairs(players:GetChildren()) do
    wait(.01)
    if v.Backpack.isPlaying.Value == true then
        _G.numberOfPlayers = _G.numberOfPlayers + 1
    end
    _G.numberOfPlayers = 0
end
0
Error:expected bool, got int hiimgoodpack 2009 — 6y
0
might want to set numberOfPlayers to 0 before the loop, not after. XAXA 1569 — 6y
0
You would use the changed event. User#5423 17 — 6y

1 answer

Log in to vote
0
Answered by 6 years ago

Other scripts can only run when this script is yielded (that is, it has called a wait command and not returned yet). Thus, you should set numberOfPlayers to 0 before updating its value. You should write your loop like this:

local players = game.Players
local isPlaying
while true do
    _G.numberOfPlayers = 0
    for i, player in ipairs(players:GetPlayers()) do
        isPlaying = v.Backpack:FindFirstChild("isPlaying")
        if isPlaying and isPlaying.Value then
            _G.numberOfPlayers = _G.numberOfPlayers + 1
        end
    end
    wait()
end

Notes:

  • use GetPlayers not GetChildren
  • wait(.01) is no less waiting than around wait(.025), so you might as well just do wait()
  • You want to wait() after fully updating numberOfPlayers, not during. As you can see, you need a while loop to continuously update the numberOfPlayers value.
  • You never need to specify == true in an if statement unless you need to differentiate between non-false/nil values. In Lua, everything that isn't false/nil evaluates to true and that's all it takes for an if statement to run.
  • I don't know if isPlaying will always be in the backpack, but - just to make sure - I used FindFirstChild so that your script won't error and then stop functioning.

It doesn't matter with such a small loop, but in general it is better to use events to maintain values (rather than a while true do loop). In this case, the events you'd need would be these:

  • When a player specifies that they are playing, increase numberOfPlayers
  • When a player specifies that they are not playing, decrease numberOfPlayers
  • When a player is leaving the game and they are playing, decrease numberOfPlayers

Again, the above script is simpler and not significantly less efficient.

0
Thanks for your help Tybearic 18 — 6y
Ad

Answer this question