Hi! I noticed a lot of on_entity_color_changed events being raised in a saved game I received for debugging one of my own mods. While it's great that we can get informed about entities changing their color, the implementation isn't optimal: The event will be raised each time LuaEntity::color is set -- even if the new color is the same as the old one!
In my own mods, I make sure that old color and new color differ before setting LuaEntity::color, using something like this:
-- Get color from name, hex, or table
ascertain_color = function(color)
assert(color, {"table", "string", "nil"}, "color, string, or nil")
local ret
local c = type(color)
-- Named colors or hex colors
if c == "string" then
ret = color:match("^#*[0-9a-fA-F]+$") and util.color(color)
if ret then
ret.a = 1
end
-- Lua color
elseif c == "table" then
-- Make sure we've got a table that only contains valid color data (empty table,
-- named keys, or index 1…4)!
if next(color) then
-- Make a copy of the color table, then remove all valid keys from it
local copy = table.deepcopy(color)
for _, i in pairs({1, 2, 3, 4, "r", "g", "b", "a"}) do
copy[i] = nil
end
-- If the copied table is not empty, the input wasn't a valid color!
if next(copy) then
return
end
end
ret = {
r = color.r or color[1] or 0,
g = color.g or color[2] or 0,
b = color.b or color[3] or 0,
a = color.a or color[4] or 1,
}
end
return ret
end
-- Compare two colors. Returns true if the colors are the same
compare_colors = function(c1, c2)
c1 = ascertain_color(c1)
c2 = ascertain_color(c2)
return c1 and c2 and util.table.compare(c1, c2)
end
It would be great if you'd add such checks as well. :-)