I need an explanation on how this works

I’ve been trying to create a custom chat GUI but hit a roadblock when I got to the colored names part. I found an old post on how to calculate the amount of spaces, but I couldn’t quite wrap my head around it when I looked at the code. Could someone explain it? Thanks in advance!

Taken from Roblox chat Utils and the solution in the old post:

function methods:GetNumberOfSpaces(str, font, textSize)
	local strSize = self:GetStringTextBounds(str, font, textSize)
	local singleSpaceSize = self:GetStringTextBounds(" ", font, textSize)
	return math.ceil(strSize.X / singleSpaceSize.X)
end

The function gets the size of the string in pixels and divides it by the size of a space in pixels to get the least number of spaces you need to fill the string.

Let’s say you have a string “AAA” and the letter “A” is 10 pixels wide, and you also have a space " " which is 5 pixels wide. The total width of “AAA” in pixels would be 30 pixels since we have 3 A’s and each is 10 pixels wide. To get the number of spaces needed to take up the same amount of space as “AAA”, we divide the width of “AAA” by the width of a space, 30 / 5 = 6 spaces.

I suggest you just use RichText so you don’t have to worry about all the complicated math.

1 Like