Page 1 of 1

How do I only color part of a string?

Posted: Sat Jun 23, 2018 5:02 pm
by ITISITHEBKID
I am working on getting text to display properly within a box. It works perfectly so far, and I have properly gotten it to identify tags. The problem comes when I try to print the text to the screen. If I have "This is <Red>text<White>", the program will properly identify red and white as tags and change the color accordingly. This is good but because the entire thing is one string, when <white> is called it just turns the whole thing red and if just red is called it turns the whole thing red. What do I need to do to fix this?

Code for identifying tags

Code: Select all

	local chars = {} --empty table. will be filled with individual charachters from (text)
	text:gsub(".",function(c) table.insert(chars,c) end) --fill table as described above
	textimer = timer:every(textspeed,function() --the timer. calls this function every textspeed of a second
		
		if chars[1] == "<" then --if the beginning of a tag
			textcolor = "" -- the color is blank
			table.remove(chars,1) --remove tag beginning 
			while chars[1] ~= ">" do --while the tag is still going on
				textcolor = textcolor .. chars[1] --the current character is added to the textcolor
				table.remove(chars,1) --and then removed from the table.
			end
			table.remove(chars,1)--this only executes once the tag is finished, because of the while function
			textcolor = _G[textcolor] --this turns the string into a variable to work with setColor
		end
In love.draw

Code: Select all

	love.graphics.setColor(0.25,0.25,0.67) -- set color to black
	love.graphics.rectangle("fill",box.x-13,box.y,box.width,Font:getHeight()*box.lines,15,15,3) -- this box is drawn first, so everything else is drawn over it. It makes the background of the box non transparent
	love.graphics.setColor(textcolor) --set color to white
	love.graphics.print(currenttext,box.x,box.y)--draw the actual text
	love.graphics.setColor(White)
	love.graphics.setLineWidth(1.5) --thicker line
	love.graphics.rectangle("line",box.x-13,box.y,box.width,Font:getHeight()*box.lines,15,15,3) --draw the box
	love.graphics.setLineWidth(1) --regular line

Re: How do I only color part of a string?

Posted: Sat Jun 23, 2018 5:48 pm
by grump
There's a built-in variant of love.graphics.print that takes a table of strings and colors and prints the strings accordingly. I recommend using that.