local str = {
["red"] = "ff0000",
["blue"] = "4C9FFF",
["purple"] = "C33AFF",
["green"] = "53FF4A",
["gray"] = "E2E2E2",
["black"] = "000000",
["white"] = "ffffff",
["pink"] = "FB8DFF",
["orange"] = "FF8E1C",
["yellow"] = "FAFF52",
--TODO Add Colors
}
function str:generate_string(text)
assert(text and type(text) == "string")
local function replaceColor(match)
local colorName = match:sub(2)
local colorValue = self[colorName]
if colorValue then
return "#" .. colorValue
else
return match
end
end
local pattern = "(&%w+)"
local result = text:gsub(pattern, replaceColor)
return result
end
local text = "&whiteHello&white World"
print(str:generate_string(text))
Hello. I have such code. I want to pass a string as an argument and inside the function, replace parts where color names are mentioned, followed by an '&' sign, with their hexadecimal code. This code works fine as long as there is a space after the last letter. For example:
"Hello&green World"
Result:
"Hello#53FF4A World"
However, if there is no space after the pattern, like:
"Hello &greenWorld"
Then the code behaves incorrectly:
Hello &greenWorld
Is there a way to fix this issue?
Also, if there's a more efficient way to implement this code, I'd appreciate your input.
I expect the code to produce such a result:
For example:
"Hello &greenWorld"
Result:
"Hello #53FF4AWorld"
Please try simpler solution as
["&green"] = "#53FF4A".