Page 1 of 1

Drawing different parts of a string with different colors.

Posted: Sat Mar 20, 2021 9:42 pm
by MadMonkeyGames
So say I have the string, "I want the word RED to be colored red." How could I make it so that the word RED is drawn red, but the rest is
drawn white? I know I would have to loop through the string somehow, but I cant quite figure out what I have to do.
Any help is appreciated!

Re: Drawing different parts of a string with different colors.

Posted: Sat Mar 20, 2021 10:23 pm
by darkfrei

Code: Select all

str_table=
{
    {text="I want the word ", color={1,1,1}},
    {text="RED", color={1,0,0}},
    {text=" to be colored red.", color={1,1,1}}
}

function printc (tabl, x,y)
    font=love.graphics.getFont()
    for i, v in ipairs (tabl) do
        love.graphics.setColor(v.color)
        love.graphics.print(v.text, x, y)
        x=x+font:getWidth(v.text)
    end
end

printc (str_table, 100, 300) -- not tested

Re: Drawing different parts of a string with different colors.

Posted: Sun Mar 21, 2021 12:05 am
by pgimeno
See love.graphics.printf#Synopsis_5.

Please note also that this forum is for posting your games and creations. Support questions should be posted in the Support and Development forum.

Re: Drawing different parts of a string with different colors.

Posted: Sun Mar 21, 2021 12:53 am
by MadMonkeyGames
darkfrei wrote: Sat Mar 20, 2021 10:23 pm

Code: Select all

str_table=
{
    {text="I want the word ", color={1,1,1}},
    {text="RED", color={1,0,0}},
    {text=" to be colored red.", color={1,1,1}}
}

function printc (tabl, x,y)
    font=love.graphics.getFont()
    for i, v in ipairs (tabl) do
        love.graphics.setColor(v.color)
        love.graphics.print(v.text, x, y)
        x=x+font:getWidth(v.text)
    end
end

printc (str_table, 100, 300) -- not tested
This is kind of what I want. I already have a table with a string, like this,
text_table = {'I want to highlight the word RED'}
Is there any way I can loop through this string and set the word RED as red?

Re: Drawing different parts of a string with different colors.

Posted: Sun Mar 21, 2021 3:36 am
by darkfrei
You can use this split string function:
https://stackoverflow.com/questions/142 ... ing-in-lua

Code: Select all

function mysplit (inputstr, sep)
        if sep == nil then
                sep = "%s" -- space symbol
        end
        local t={}
        for str in string.gmatch(inputstr, "([^"..sep.."]+)") do
                if str== "RED" then print ('the RED str!') end
                table.insert(t, str)
        end
        return t
end