Scripting HelpersARCHIVE
A little piece of Roblox history. Preserved for everyone, one question at a time.Read about the archive →
✓ ANSWER ACCEPTED

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

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

3 comments

0

Error:expected bool, got int

0

might want to set numberOfPlayers to 0 before the loop, not after.

0

You would use the changed event.

1 answer

✓ 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.

1 comment

0

Thanks for your help

This discussion is preserved as it was. New answers, comments, and votes are closed.