Fix colorspec.from_string, add tests

This commit is contained in:
Lars Mueller 2021-03-27 12:18:27 +01:00
parent 0c47e04347
commit 6f0dbaaeb3
2 changed files with 20 additions and 7 deletions

@ -165,14 +165,16 @@ end
colorspec.from_table = colorspec.new colorspec.from_table = colorspec.new
function colorspec.from_string(string) function colorspec.from_string(string)
local hex = "#([A-Fa-f%d])+" local hex = "#([A-Fa-f%d]+)"
local number, alpha = named_colors[string], 0xFF local number, alpha = named_colors[string], 0xFF
if not number then if not number then
local name, alpha_text = string:match("^([a-z])+" .. hex .. "$") local name, alpha_text = string:match("^([a-z]+)" .. hex .. "$")
if name then
assert(alpha_text:len() == 2) assert(alpha_text:len() == 2)
number = assert(named_colors[name]) number = assert(named_colors[name])
alpha = tonumber(alpha_text, 16) alpha = tonumber(alpha_text, 16)
end end
end
if number then if number then
return colorspec.from_number(number * 0x100 + alpha) return colorspec.from_number(number * 0x100 + alpha)
end end

@ -113,8 +113,19 @@ do
end end
-- colorspec -- colorspec
local colorspec = minetest.colorspec.from_number(0xDDCCBBAA) local colorspec = minetest.colorspec
assertdump(table.equals(colorspec, {a = 0xAA, b = 0xBB, g = 0xCC, r = 0xDD,}), colorspec) local function test_from_string(string, number)
local spec = colorspec.from_string(string)
local expected = colorspec.from_number(number)
assertdump(table.equals(spec, expected), {expected = expected, actual = spec})
end
local spec = colorspec.from_number(0xDDCCBBAA)
assertdump(table.equals(spec, {a = 0xAA, b = 0xBB, g = 0xCC, r = 0xDD}), spec)
test_from_string("aliceblue", 0xf0f8ffff)
test_from_string("aliceblue#42", 0xf0f8ff42)
test_from_string("#333", 0x333333FF)
test_from_string("#694269", 0x694269FF)
test_from_string("#11223344", 0x11223344)
-- k-d-tree -- k-d-tree
local vectors = {} local vectors = {}