From e048fb3b0342192d7aeb82cc2ee2f50a92be6c3b Mon Sep 17 00:00:00 2001 From: Lars Mueller Date: Sat, 13 Nov 2021 23:57:32 +0100 Subject: [PATCH] colorspec.from_string(): return nothing if invalid --- minetest/colorspec.lua | 27 ++++++++++++++++++--------- test.lua | 4 ++-- 2 files changed, 20 insertions(+), 11 deletions(-) diff --git a/minetest/colorspec.lua b/minetest/colorspec.lua index d32d72a..b5656c8 100644 --- a/minetest/colorspec.lua +++ b/minetest/colorspec.lua @@ -203,22 +203,29 @@ function colorspec.from_string(string) if not number then local name, alpha_text = string:match("^([a-z]+)" .. hex .. "$") if name then - assert(alpha_text:len() == 2) - number = assert(named_colors[name]) + if alpha_text:len() ~= 2 then + return + end + number = named_colors[name] + if not number then + return + end alpha = tonumber(alpha_text, 16) end end if number then - return colorspec.from_number(number * 0x100 + alpha) + return colorspec.from_number_rgba(number * 0x100 + alpha) end local hex_text = string:match("^" .. hex .. "$") - assert(hex_text, "invalid colorstring") + if not hex_text then + return + end local len, num = hex_text:len(), tonumber(hex_text, 16) if len == 8 then - return colorspec.from_number(num) + return colorspec.from_number_rgba(num) end if len == 6 then - return colorspec.from_number(num * 0x100 + 0xFF) + return colorspec.from_number_rgba(num * 0x100 + 0xFF) end if len == 4 then return colorspec.from_table{ @@ -235,8 +242,6 @@ function colorspec.from_string(string) r = (floor(num / (16 ^ 2)) % 16) * 17 } end - -- TODO return nil - error"invalid colorstring" end colorspec.from_text = colorspec.from_string @@ -308,5 +313,9 @@ function colorspec:to_number() end colorspec_to_colorstring = minetest.colorspec_to_colorstring or function(spec) - return colorspec.from_any(spec):to_string() + local color = colorspec.from_any(spec) + if not color then + return nil + end + return color:to_string() end diff --git a/test.lua b/test.lua index 9484a8b..4de3883 100644 --- a/test.lua +++ b/test.lua @@ -331,7 +331,7 @@ assert(minetest.luon:read_string(minetest.luon:write_string(ItemStack""))) local colorspec = minetest.colorspec local function test_from_string(string, number) local spec = colorspec.from_string(string) - local expected = colorspec.from_number(number) + local expected = colorspec.from_number_rgba(number) assertdump(table.equals(spec, expected), {expected = expected, actual = spec}) end local spec = colorspec.from_number(0xDDCCBBAA) @@ -341,7 +341,7 @@ test_from_string("aliceblue#42", 0xf0f8ff42) test_from_string("#333", 0x333333FF) test_from_string("#694269", 0x694269FF) test_from_string("#11223344", 0x11223344) -assert(colorspec.from_string"#694269":to_string() == "694269") +assert(colorspec.from_string"#694269":to_string() == "#694269") -- Persistence local function test_logfile(reference_strings)