@janpieterkes (janpieterkes) posted a new topic, subject "Why does this script run 1 time? (Sometimes 2)". It read:

   This script doesn't always run when it's supposed to (When it doesn't it gives the error “Scirpt timeout: exhausted execution time”)
    [code] 
        if RandomPlayer1.Name == RandomPlayer2.Name then
        					print("Oops")
        					print(PickablePlayers)
        					table.remove(PickablePlayers,2,RandomPlayer2)
        					local Check = true
        					while Check == true do
        						wait(0.2)
        						RandomPlayer2 = Players[math.random(#PickablePlayers)]
        						if RandomPlayer1.Name ~= RandomPlayer2.Name then
        							Check = false
        						end
        					end
        				end
        
    [/code]

So @mari230899 (Pyracolle) replied

    I think the error occurs because you must put the “if” before the command, therefore sometimes it works and sometimes it doesnt, but I recommend this:
    [code] 
        local Check = true
        	repeat
        		wait(0.5)
        		RandomPlayer2 = Players[math.random(#PickablePlayers)]
        	until
        	RandomPlayer1.Name ~= RandomPlayer2.Name
        
        	Check = false
        
    [/code]

So @janpieterkes (janpieterkes) replied

    It doesn't run at all if I use this.

So @Keneyaz (Koyuki) replied

    In the if statement (of your original code) you need to add a `break` under `Check = false` else it will keep running, also use `task.wait()`, instead of `wait()`.

Then @janpieterkes (janpieterkes) said

    What's the difference between wait() and task.wait()?

Then @SelDraken (SelDraken) said

    Task Library - Now Available! Announcements
    
    > Hey developers, We have just enabled a brand new library that you can use in your projects. The task library allows you to talk directly with our engine's task scheduler to manage and schedule code. It features a number of new methods as well as some improvements to existing methods. Details task.spawn Takes a thread or function and resumes it immediately through the engine's scheduler. Additional arguments are passed to the thread or function being resumed. void task.spawn(function | thread,…

So @Katrist (Katrist) replied

    Task.wait() vs wait() Scripting Support
    
    > I've heard a lot of people say to use task.wait() instead of wait(). Is there any situations where you would use wait() over task.wait() or is task.wait() just definitively better? Any help is appreciated.

After which, @wf_sh (YoungPencilSharpner) added

    This is caused by the loop running infinitely in cases where the loop does not meet the requirements that you set for it to end. In your code you have only give math.random 1 argument when it requires 2 (min,max) which is most likely the cause of it never picking a valid player. Try this (hopefully improved) snippet and tell me if it works.
    [code] 
        if RandomPlayer1 == RandomPlayer2 then
        	print("Oops")
        	print(PickablePlayers)
        	table.remove(PickablePlayers,2,RandomPlayer2)
            repeat
                RandomPlayer2 = Players[math.random(1,#PickablePlayers)]
                task.wait(.2)
        	until RandomPlayer1 ~= RandomPlayer2
        end
    [/code]

So @Rescripted_Developer (PixelatedCherry) replied

    you might want to try adding a wait to the 2nd line of code, for example. wait(0.1).

To which @Sleazel (Sleazy_Weasel) replied

    That is incorrect usage of `table.remove()`. To remove element from an array, first you need to find it. `table.remove` accepts only 2 arguments, and the third one will be ignored.  
    To remove `RandomPlayer2` from the array use:
    [code] 
        table.remove(PickablePlayers,table.find(PickablePlayers,RandomPlayer2))
        
    [/code]
    
    Now I am not 100% sure what you are trying to achieve with the `while` loop, but it seems redundant. It looks like theres an error at this line:
    [code] 
        RandomPlayer2 = Players[math.random(#PickablePlayers)]
        
    [/code]
    
    Whatever `Player` array is, I am pretty sure indexes will not match with the `PickablePlayers` array, especially after `table.remove()`  
    I think it should rather be written this way:
    [code] 
        RandomPlayer2 = PickablePlayers[math.random(#PickablePlayers)]
        
    [/code]
    
    If so, while loop should no longer be necessary.

To which @janpieterkes (janpieterkes) replied

    It does what it's supposed to do, but for some reason it keeps running for an infinite amount of times.

So @janpieterkes (janpieterkes) replied

    [code]
        RandomPlayer2 = PickablePlayers[math.random(#PickablePlayers)]
        
    [/code]
    
    This returns `nil` for some reason.

After which, @wf_sh (YoungPencilSharpner) added

    It appears my code snippet didn't work as I didn't spot the error with table.remove, however I told you that the reason that line is incorrect is because math.random requires a minimum and a maximum argument where you have only given it 1. Replacing it with `RandomPlayer2=PickablePlayers[math.random(1,#PickablePlayers)]`  
    Should work

So @janpieterkes (janpieterkes) replied

    Code I currently use;
    [code] 
        if RandomPlayer1 == RandomPlayer2 then
        					print("Oops")
        					print(PickablePlayers)
        					RandomPlayer2 = PickablePlayers[math.random(1,#PickablePlayers)]
        					repeat
        						RandomPlayer2 = Players[math.random(1,#PickablePlayers)]
        						task.wait(.2)
        						print(RandomPlayer1,RandomPlayer2)
        					until RandomPlayer1 ~= RandomPlayer2
        				end
        
    [/code]
    
    For some reason RandomPlayer1 and RandomPlayer2 become the same player.

Then @wf_sh (YoungPencilSharpner) said

    Not sure about the problem with it, can you post possibly a larger snippet of your code? also try testing this with 3-4 players rather then 2 if you haven't already.

After which, @janpieterkes (janpieterkes) added

    [code]
        		elseif ChosenEvent == "Event9" then
        			local Players = game.Players:GetPlayers()
        			local CountValue = Instance.new("IntValue",game.Workspace)
        			local Number = 0
        			for i, Count in pairs(Players) do
        				local Number = Number + 1
        				CountValue.Value = Number
        			end
        			wait(0.2)
        			if CountValue.Value >= 1 or CountValue.Value == 2 then
        				print("2playersingame")
        				local PickablePlayers = {game.Players:GetPlayers()}
        				local Players = game.Players:GetChildren()
        				local RandomPlayer1 = Players[math.random(#Players)]
        				local RandomPlayer2 = Players[math.random(#Players)]
        				if RandomPlayer1 == RandomPlayer2 then
        					print("Oops")
        					print(PickablePlayers)
        					RandomPlayer2 = PickablePlayers[math.random(1,#PickablePlayers)]
        					repeat
        						RandomPlayer2 = PickablePlayers[math.random(1,#PickablePlayers)]
        						task.wait(.2)
        						print(RandomPlayer1,RandomPlayer2)
        					until RandomPlayer1 ~= RandomPlayer2
        				end
        				local P1Char = RandomPlayer1.Character:GetChildren()
        				local P2Char = RandomPlayer2.Character:GetChildren()
        				print(RandomPlayer1.Name)
        				print(RandomPlayer2.Name)
        				if P1Char and P2Char then
        					for i, Part in pairs(P1Char) do
        						if Part:IsA("BasePart") then
        							Part.Transparency = 1
        						end
        						if Part:IsA("Accessory") then
        							Part:Destroy()
        						end
        					end
        					for i, Part in pairs(P2Char) do
        						if Part:IsA("BasePart") then
        							Part.Transparency = 1
        						end
        						if Part:IsA("Accessory") then
        							Part:Destroy()
        						end
        					end
        					wait(3)
        					for _, Part in pairs(P1Char) do
        						if Part:IsA("BasePart") then
        							Part.Transparency = 0
        						end
        						if Part.Name == "HumanoidRootPart" then
        							Part.Transparency = 1
        						end
        					end
        					for _, Part in pairs(P2Char) do
        						if Part:IsA("BasePart") then
        							Part.Transparency = 0
        						end
        						if Part.Name == "HumanoidRootPart" then
        							Part.Transparency = 1
        						end
        					end
        				end
        			else
        				print("Only 1 player in game")
        				local RandomPlayer1 = Players[math.random(#Players)]
        				local Char = RandomPlayer1.Character
        				if Char then
        					for i, Part in pairs(Char:GetChildren()) do
        						if Part:IsA("BasePart") then
        							Part.Transparency = 1
        						end
        						if Part:IsA("Accessory") then
        							Part:Destroy()
        						end
        					end
        					wait(5)
        					for i, Part in pairs(Char:GetChildren()) do
        						if Part:IsA("BasePart") then
        							Part.Transparency = 0	
        						end
        						if Part.Name == "HumanoidRootPart" then
        							Part.Transparency = 1
        						end
        					end
        					CountValue:Destroy()
        
    [/code]
    
    (Testing with more players doesn't make a difference)

So @wf_sh (YoungPencilSharpner) replied

    I'll read it line by line and spot errors.  
    `if CountValue.Value >= 1 or CountValue.Value == 2 then`, this line can return true if there is 1 OR more players. Replace it with `If CountValue.Value > 1 then`
    
    `local RandomPlayer1 = Players[math.random(#Players)]` math.random requires 2 arguments, a minimum and maximum value. Replace with `local RandomPlayer1 = Players[math.random(1,#Players)]`
    
    `local RandomPlayer2 = Players[math.random(#Players)]` same issue
    [code] 
        print("Only 1 player in game")
        local RandomPlayer1 = Players[math.random(#Players)]
        
    [/code]
    
    same issue
    
    Also consider replacing all of your instances of `wait()` with the new improved `task.wait()`

Then @janpieterkes (janpieterkes) said

    Nothing changed, but I noticed that both players get put under the same value in the table is that supposed to happen?

To which @wf_sh (YoungPencilSharpner) replied

    Referring to which table exactly?

To which @janpieterkes (janpieterkes) replied

    The PickablePlayers table (Character limit)

@wf_sh (dotdelay) replied

    Guess who found the solution!  
    
    
    image1066×622 124 KB
    
      
    Turns out due to the `local PickablePlayers = {game.Players:GetPlayers()}` line RandomPlayer1 and 2 where being set to table values. The :GetPlayers() function already returns a table so no need to add extra brackets around em! no clue why my pea brain didnt spot this. Here is the working code
    [code] 
        local Players = game.Players:GetPlayers()
        
        local CountValue = Instance.new("IntValue")
        CountValue.Parent = workspace
        for i, Count in pairs(Players) do
        	CountValue.Value = i
        end
        
        if CountValue.Value > 1 then
        	print("2playersingame")
        	local PickablePlayers = game.Players:GetPlayers()
        	local RandomPlayer1 = PickablePlayers[math.random(1,#PickablePlayers)]
        	local RandomPlayer2 = PickablePlayers[math.random(1,#PickablePlayers)]
        	if RandomPlayer1 == RandomPlayer2 then
        		print("Oops")
        		repeat
        			RandomPlayer2 = PickablePlayers[math.random(1,#PickablePlayers)]
        			task.wait(.2)
        			print(RandomPlayer1,RandomPlayer2)
        		until RandomPlayer1 ~= RandomPlayer2
        	end
        	local P1Char = RandomPlayer1.Character:GetChildren()
        	local P2Char = RandomPlayer2.Character:GetChildren()
        	print(RandomPlayer1.Name,RandomPlayer2.Name)
        	if P1Char and P2Char then
        		print("Running code")
        		for i, Part in pairs(P1Char) do
        			if Part:IsA("BasePart") then
        				Part.Transparency = 1
        			end
        			if Part:IsA("Accessory") then
        				Part:Destroy()
        			end
        		end
        		for i, Part in pairs(P2Char) do
        			if Part:IsA("BasePart") then
        				Part.Transparency = 1
        			end
        			if Part:IsA("Accessory") then
        				Part:Destroy()
        			end
        		end
        		task.wait(3)
        		for _, Part in pairs(P1Char) do
        			if Part:IsA("BasePart") then
        				Part.Transparency = 0
        			end
        			if Part.Name == "HumanoidRootPart" then
        				Part.Transparency = 1
        			end
        		end
        		for _, Part in pairs(P2Char) do
        			if Part:IsA("BasePart") then
        				Part.Transparency = 0
        			end
        			if Part.Name == "HumanoidRootPart" then
        				Part.Transparency = 1
        			end
        		end
        	end
        end
    [/code]

Then @janpieterkes (janpieterkes) said

    Thank you very much, I would never have figured that out on my own!


{'source': 'discourse', 'url': 'https://devforum.roblox.com/t/why-does-this-script-run-1-time-sometimes-2/1604773', 'title': 'Why does this script run 1 time? (Sometimes 2)', 'views': 597, 'has_accepted_answer': True, 'word_count': 1303, 'like_count': 8, 'reply_count': 16, 'participant_count': 8, 'posts': 22, 'tags': '', 'author': '@janpieterkes (janpieterkes)', 'participants': '@janpieterkes (janpieterkes), @mari230899 (Pyracolle), @Keneyaz (Koyuki), @SelDraken (SelDraken), @Katrist (Katrist), @wf_sh (YoungPencilSharpner), @Rescripted_Developer (PixelatedCherry), @Sleazel (Sleazy_Weasel), @wf_sh (dotdelay)', 'image_url': [None], 'created_at': '2021-12-28T15:34:35.540Z', 'last_posted_at': '2021-12-31T13:36:28.471Z'}