Stack overflow trying to recreate file.Write

Hello
I’ve been having a little trouble recreating the old way gmod did file.Write where it auto-made the directories for you. It seems to give me a stack overflow. Can anyone explain what the issue is please?

[lua]
function oldfileWrite(fileName,text)

--Count occurences of slash in fileName
local slashCount=0
for letter=1,string.len(fileName) do		
	if string.sub(fileName,letter,letter)=="/" then
		slashCount=slashCount+1
	end
end

--Make sure that we're going down directories
if slashCount>0 then

	local fileDirs=string.Explode("/",fileName)
	local fileNameAdd=fileDirs[1]
	for i,dir in pairs(fileDirs) do
		if i>1 and not file.Exists(fileNameAdd,"DATA") and not string.match(fileNameAdd,"%.txt") then
			file.CreateDir(fileNameAdd)
			fileNameAdd=fileNameAdd.."/"..dir	
		end
	end
end

file.Write(fileName,text)

end[/lua]

the errors

You could try something like this :
[lua]
function file.OWrite( name, text, delim )

delim = delim or "/";

local tbl = string.Explode( delim, name );

for k, dir in pairs( tbl )

	if ( #tbl == dir ) then 

		file.Write( name, text );

	else 

		file.CreateDir(dir);

	end

end

end
[/lua]


function MakeDir( path )
	print( path )
end

function MakeDirTree( path )
	local tree = ""
	
	for k in path:gmatch( "[^/\\]+" ) do
		if k:match( "%..-$" ) then
			break
		end
		
		tree = tree .. k
		
		MakeDir( tree )
		
		tree = tree .. "/"
	end
end

MakeDirTree( "characters/123546/saves/file.txt" )

[lua]

function HeX.file.MakeTreeForFile(path) --Make dir tree, WHY GARRY
local Tab = string.Explode("/",path)
local Here = “”
for k,v in ipairs(Tab) do
if k != #Tab then --Last entry in path table
Here = Here…v…"/"
end
end
if not file.IsDir(Here, “DATA”) then
file.CreateDir(Here, “DATA”)
end
end

function HeX.file.Write(path,cont)
HeX.file.MakeTreeForFile(path)

--Write
local Out = file.Open(path, "w", "DATA")
	if not Out then return end
	Out:Write(cont)
Out:Close()

end
[/lua]

Thank you all for the help! Just for learning sake however, what was wrong with my code that caused this problem?

Despite the code not working, the function you posted won’t cause stack overflows.