Okay so basically I’m working on a colour wheel which gives as many options to the player as possible which is going fine. However, I want to make it so if the string doesn’t match “#______”, it replaces any invalid characters at the end with zeroes
So basically, let’s say the user’s text box says “#00C”, it should replace with #00C000 because of the last missing zeroes, my methodology was something like this, where each line represents a character:
# -- first character should always be a hash symbol
_ -- if the character is not hexadecimal or doesn't exist, replace this slot with 0
_ -- if the character is not hexadecimal or doesn't exist, replace this slot with 0
-- and so on for a total of 6 times
then, do string:sub(1,7) for the final string to be displayed.
Is there a shorthand method of doing this with string.match/format or something? Or do I have to use string.split and weed out what isn’t valid?
Use string.gsub to replace non-hexadecimal characters [^%x] with "0".
-- string argument str should start with #
-- string return value starts with # and is followed by 6 hex digits
local function fixup(str)
-- remove the # and shorten to up to 6 chars
str = str:sub(2, 7)
-- replace invalid characters with 0
-- %x is hexadecimal digits
str = str:gsub("[^%x]", "0")
-- uppercase
-- str = str:upper()
-- right-pad with 0
str = str .. string.rep("0", 6 - #str)
-- prepend #
return "#" .. str
end
print(fixup("#7f7fff"))
print(fixup("#1Y2f)e8"))
print(fixup("#"))
print(fixup("orange")) -- uhh, no
If your color wheel must only take color names starting with #, then please consider putting the # in a separate textlabel (so that it’s there, but does not invade the input) and only dealing with text that does not contain the #.
The # is always there, so save the user the effort of writing it.