color: Use color_mt and normal indexing

Fix #34.

Set color_mt on new colors so add, subtract, multiply, is_color work.

We don't use ffi for color (32cf0e8), so remove cdata check for 0-based
offset indexing.

Add tests for creating colours and using operators.
This commit is contained in:
David Briscoe 2022-03-26 23:15:28 -07:00
parent ea79f346f6
commit 509594aec2
2 changed files with 31 additions and 22 deletions

View File

@ -10,7 +10,7 @@ local color_mt = {}
local function new(r, g, b, a)
local c = { r, g, b, a }
c._c = c
return setmetatable(c, color)
return setmetatable(c, color_mt)
end
-- HSV utilities (adapted from http://www.cs.rit.edu/~ncs/color/t_convert.html)
@ -341,24 +341,7 @@ function color.to_string(a)
return string.format("[ %3.0f, %3.0f, %3.0f, %3.0f ]", a[1], a[2], a[3], a[4])
end
function color_mt.__index(t, k)
if type(t) == "cdata" then
if type(k) == "number" then
return t._c[k-1]
end
end
return rawget(color, k)
end
function color_mt.__newindex(t, k, v)
if type(t) == "cdata" then
if type(k) == "number" then
t._c[k-1] = v
end
end
end
color_mt.__index = color
color_mt.__tostring = color.to_string
function color_mt.__call(_, r, g, b, a)

View File

@ -1,10 +1,37 @@
local color = require "modules.color"
local DBL_EPSILON = require("modules.constants").DBL_EPSILON
local function assert_is_float_equal(a, b)
if math.abs(a - b) > DBL_EPSILON then
assert.is.equal(a, b)
end
end
describe("color:", function()
it("operators: add, subract, multiply", function()
local c = color(1,1,1,1)
assert.is_true(c:is_color())
local r = c + c
assert.is_true(r:is_color())
assert_is_float_equal(r[1], 2)
assert_is_float_equal(r[2], 2)
assert_is_float_equal(r[3], 2)
r = c - c
assert.is_true(r:is_color())
assert_is_float_equal(r[1], 0)
assert_is_float_equal(r[2], 0)
assert_is_float_equal(r[3], 0)
r = c * 5
assert.is_true(r:is_color())
assert_is_float_equal(r[1], 5)
assert_is_float_equal(r[2], 5)
assert_is_float_equal(r[3], 5)
end)
end)
--[[
new(r, g, b, a)
from_hsv(h, s, v)
from_hsva(h, s, v, a)
invert(c)
@ -19,6 +46,5 @@ saturation(color, percent)
value(color, percent)
gamma_to_linear(r, g, b, a)
linear_to_gamma(r, g, b, a)
is_color(a)
to_string(a)
--]]
--]]