Problem with tables and pairs loop

After adding the loop (on line 4), the code stopped working. It gets to 4 lines and then completely breaks off. Well, in general, before that, he was also not perfect, but now I just don’t know what to do. Can someone help me? From this fuss with tables and cycles my head hurts.

--[[
players = {
	[1] = {
		[1] = game:GetService("Players").shheker,
		[2] = "Dire",
                [3] = 600,
                [4] = 240
	},
}

heroes = {
	["Hero1"] = {}
}

visualization of players and heroes
]]

local turn = "Dire"
local countdire = 0
local countradiant = 0
local needtopickdire = 2
local needtopickradiant = 2

stage.OnServerEvent:Connect(function(player, hero)
	for _,v in ipairs(players) do
		for i,_ in pairs(heroes) do
			if table.find(v, "Dire") or table.find(v, "Radiant") then
				for i,v1 in ipairs(v) do
					if i == hero then
						if table.find(v, player) then
							if heroes[hero] then
								if not table.find(v, hero) then
									if v1 == "Dire" or v1 == "Radiant" then
										if v1 == turn then
											table.insert(v, i)
										end
									end
								end
							end
						end
					end
					
					if v1 == "Dire" then
						countdire += 1
					end				
					if v1 == "Radiant" then
						countradiant += 1
					end
				end
			end
		end
	end
	
	if countdire < 2 then
		needtopickdire = 1
		if countdire == 0 then
			needtopickdire = 0
		end
	end
	
	if countradiant < 2 then
		needtopickradiant = 1
		if countradiant == 0 then
			needtopickradiant = 0
		end
	end
	print(countdire .. " " .. needtopickdire .. " " .. countradiant .. " " .. needtopickradiant)
end)
1 Like

That’s a lot of nested loops. I’d suggest recursion for this:

function traverse(iter)
    for k, v in pairs(iter) do
        if typeof(iter) == "table" then
            traverse(v)
            continue
        end

    if table.find(v, "Dire") or table.find(v, "Radiant") then
        traverse(v)
        continue
    end
end

… etc. Once you refactor your code to look something like this, it’ll be easier to piece together what’s wrong!