My cellular automata isn't working

I applied simple rules (convay’s game of life rules) to my script but when i runned it just created complete chaos instead of cells in somewhat order


This is part of my script that actually matters

local die_MAX = 4
local die_MIN = 1
local Rep_MIN = 2
local Survive = 3
local s = 4
local maping = 1
function GenerateStep (cells)
	local NewMap = {}
	for x = 1,Xs do
		for z = 1,Zs do
			local myName = x.."."..z
			local myCell = cells:FindFirstChild(myName)
			if myCell then
				local count = 0
				for xM = -maping,maping do
					for zM = -maping,maping do
						local name = (x+xM).."."..(z+zM)
						local cell = cells:FindFirstChild(name)
						if cell and myCell ~= cell then
							local color = cell.BrickColor
							if color == BrickColor.Black() then
								count += 1
							end
						end
					end
				end
				if count <= die_MIN or count >= die_MAX then
					NewMap[myName] = false
				elseif count >= Rep_MIN then
					NewMap[myName] = true
				elseif count == Survive then
					if myCell.BrickColor == BrickColor.White() then
						NewMap[myName] = false
					else
						NewMap[myName] = true
					end
				end
			end
		end
	end
	for name,v in pairs(NewMap) do
		local div = string.split(name,".")
		local x,z = div[1],div[2]
		local cell = cells:FindFirstChild(name)
		if cell then
			if v == true then
				cell.BrickColor = BrickColor.Black()
			else
				cell.BrickColor = BrickColor.White()
			end
		end
	end
	return true
end 

I’d suggest you start by refactoring your code so it’s more readable. Try creating a matrix using tables (2D array) with bool values to indicate whether a cell is active or not. That way you can start to build separate functions that can easily check if the cell adjacent in any direction is active or not. It’ll make implementing the rules for game of life a lot easier and clearer. Then once you’ve determined the new cell activations in your matrix you can finally write the cells out to the world (changing brick colours).