Possible to "Sort Palette" via Script/lua?


I’m creating a script for my project, and I couldn’t find a way to sort the palette via scripting/lua.

Thanks in advance!

I don’t think I’ve seen a command to sort the palette. A workaround, if you’re interested, is below.

---@param a Color left
---@param b Color right
---@return boolean
local function hsiComparator (a, b)
    if a.alpha <= 0 then return true end
    if b.alpha <= 0 then return false end
    local aHsi <const> = (a.red + a.green + a.blue) / 3.0
    local bHsi <const> = (b.red + b.green + b.blue) / 3.0
    return aHsi < bHsi

local sprite <const> = app.sprite
if not sprite then return end

local palette <const> = sprite.palettes[1]
local lenPalette <const> = #palette

---@type Color[]
local colors <const> = {}
local i = 0
while i < lenPalette do
    colors[1 + i] = palette:getColor(i)
    i = i + 1

table.sort(colors, hsiComparator)

app.transaction("Set Colors", function()
    local j = 0
    while j < lenPalette do
        palette:setColor(j, colors[1 + j])
        j = j + 1

If you want a reference for how the built-in palette sorting works, check out the source code:

1 Like