Iterating through table not working correctly or something?

Hello fellow people!
I need some help in finding out why my script will not work properly. Here is this module to disable/enable guis:

--//Services and Player
local PS = game:GetService("Players")

local Player = PS.LocalPlayer
local PlayerGui = Player:WaitForChild("PlayerGui")
--//Module Functions

local Functions = {}

local ActiveGuis = {}


function Functions:DisableActiveGuis(ExclusionTable)
	for i, Gui in pairs(PlayerGui:GetDescendants()) do
		if Gui:IsA("ScreenGui") then
			--Make so that if gui is part of exclusion then leave it else disable and add gui to ArtiveGuis table
			if ExclusionTable then
				if table.find(ExclusionTable, Gui) then
					print("Exclusion: ", Gui)
					continue
				end
			end
			if Gui.Enabled == true then
				Gui.Enabled = false
				print("Disabled: ", Gui)
				table.insert(ActiveGuis, Gui)
			end
		end
	end
end

function Functions:EnableInactiveGuis()
	for i,Gui in ipairs(ActiveGuis) do
		if Gui:IsA("ScreenGui") then
			Gui.Enabled = true
			print(Gui, "REMOVED")
			table.remove(ActiveGuis, i)
		else
			warn("What", Gui)
		end
	end
	print(ActiveGuis)
end

return Functions

Now clearly it looks fine right? NO! For some reason some guis just don’t get enabled again when the second function is called. Here is a output ss:


Maybe something to do with the gui itself?
Thanks!

When you use table.remove inside the loop, it modifies the ActiveGuis table while you’re iterating over it.
try this:

function Functions:EnableInactiveGuis()
    for i = #ActiveGuis, 1, -1 do
        local Gui = ActiveGuis[i]
        if Gui and Gui:IsA("ScreenGui") then
            Gui.Enabled = true
            print(Gui, "REMOVED")
        else
            warn("What", Gui)
        end
    end
    ActiveGuis = {}
    print(ActiveGuis)
end
1 Like

AYY this works! Thanks:


Also can you explain how this loop works and like whyd you put for i = #ActiveGuis, 1, -1 do?

1 Like

this is a reverse for loop.

for i = Start, Ending, theStep do

which means the loop will go reversed from the amount of your ActiveGuis by decreasing -1 each time until it hit 1, the loop will keep running as long as i is greater than 1

1 Like

This makes sense, thank you!
I hope you have a great day :pray:

1 Like

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.