Why does string.gsub behave weirdly?

This is code:

function ToString(Path: Instance)
	local Path = Path:GetFullName()
	
	return string.gsub(Path, ".", "\\")
end

Although it may seem simple, it is…

Output:

  19:43:29.832  > function ToString(Path: Instance)
	local Path = Path:GetFullName()
	
	return string.gsub(Path, ".", "\\")
end print(ToString(workspace.Room.Part))  -  Studio
  19:43:29.833  \\\\\\\\\\\\\\\\\\\ 19  -  edit

How to repair??

In string.gsub, the . character means replace every character in the string (see picture below)

What you want, is to escape it instead:

function getPath(path: Instance): string
    -- Escape the . by putting a % infront of it.
    return string.gsub(path:GetFullName(), "%.", "\\")
end

local scriptPath, _ = getPath(script)
print(scriptPath) -- yada yada whatever prints
1 Like

This works, thank you so much [String]

1 Like

Haha no problem! Hope it works :slight_smile: