This has an improvement over the unit's name conversion as it doesn't allocate a dynamic function to handle the
string.gsub() call and it's kept on C side. The way I have the coloring work is it starts as green at 100%, moves to yellow at 50% and red at 0%. The way text colors work is they use UI escape sequences. The one for colors is in the format
|cAARRGGBB in which
AA,
RR,
GG, and
BB represent hex values for
Alpha,
Red,
Green, and
Blue respectively. Although it should be customary to use
|r as an end tag for colored text, it's not necessary if you're immediately changing to another color for following text. The purpose of
|r is to reset the color of following text to what is set by the object that is given the string to display. The use of
|| is to print a literal pipe character "|" as this is used for the UI escape sequences.
Code:
function(unit)
local short=(UnitName(unit) or unit):gsub("(%S)%S*%s+","%1%.");
local pcnt=math.min(1,UnitHealth(unit)/UnitHealthMax(unit));-- If max is zero (it happens) assume 100%
local r,g=math.max(0,2-pcnt*2)*255,math.min(1,pcnt*2)*255;
return ("|cffffffff%s || |cff%02x%02x00%.0f|r"):format(short,r,g,pcnt*100));
end
This is to get dynamic text colors to work in a string-only standpoint, but it'll be much better to leave the static colors in the string and control the dynamic color from a FontString object. The following code makes use of this.
Code:
function(obj,unit)
local short=(UnitName(unit) or unit):gsub("(%S)%S*%s+","%1%.");
local pcnt=math.min(1,UnitHealth(unit)/UnitHealthMax(unit));-- If max is zero (it happens) assume 100%
obj:SetTextColor(math.max(0,2-pcnt*2),math.min(1,pcnt*2),0);
obj:SetFormattedText("|cffffffff%s |||r %.0f",short,pcnt*100));
end
UI Escapes (WoWPedia)