✓ Accepted answer
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.
3 comments
Error:expected bool, got int
might want to set numberOfPlayers to 0 before the loop, not after.
You would use the changed event.