• Subject: Re: argument alternative
• From: Pierre-Yves Gérardy <pygy79@...>
• Date: Wed, 24 Feb 2010 12:43:26 +0100

```Here's some code I use in LÖVE to solve a similar problem, but with a
different approach:

In LÖVE, all functions that take a color as input actually simply take
r,g,b,a parameters (range 0-255)
So I use a variation on the tupple pattern.

red = color.rgba(255,0,0)

you can pass around the red object, and then call red() where you want
to unpack it.

setColor(red())

is translated to

setColor(255,0,0,255)

The API works as follows:

solidGrey=color.rgba(192)
translucentGrey=color.rgba(192,128)

solidGrey()        -- => 192,192,192,255
translucentGrey()  -- => 192,192,192,128

solidGreen=color.rgba(0,255,0)
translucentGreen=color(0,255,0,128)

solidGreen()       -- => 0,255,0,255
solidGreen(64)     -- => 0,255,0,64

solidRed=color.hsla(0)
color.setAlpha(169)

solidRed() -- => 255,0,0,169

pink = color.hsla(0,192,255)
blue = color.rgba("#0000ff")

-- The code:

function arityfunction( T, error_ )
if error_ then
setmetatable( T, {__index=function( t, i ) error( tostring( error_ ) ) end} )
end
return function(...)
return T[#{...}](...) -- the use of #{...} is intentional.end
end
end

do
color={}

local globalalpha=255

color.setAlpha=function( alpha ) globalalpha=alpha end

local function createColorObject(r,g,b,a)
-- you can use the weak table trick from the PiL
-- to memoize your color objects if you want to.
return function( alpha )
return r, g, b, alpha and alpha or a or globalalpha
end
end

local _rgba=arityfunction( {
[1]=function(i)       return createColorObject(i,i,i)    end,
[2]=function(i,a)     return createColorObject(i,i,i,a)  end,
[3]=function(r,g,b)   return createColorObject(r,g,b)    end,
[4]=function(r,g,b,a) return createColorObject(r,g,b,a)  end
},"color.rgba() accepts 1 to 4 parameters")

function color.rgba(...)
local s, alpha = {...}[1], {...}[2]
if type(s)=="string" then
local r,g,b

error("the \"#rrggbb\" syntax isn't implemented yet")

return createColorObject(r, g, b, alpha)
else
return _rgba(...)
end
end

local function _hsla(h,s,l,a)
local r,g,b

-- convert hsl to rgb here

error("_hsla isn't impelemented yet")

return createColorObject(r,g,b,a)
end

color.hsla=arityfunction({
[1]=function(h)       return _hsla(h,255,255)   end,
[2]=function(h,a)     return _hsla(h,255,255,a) end,
[3]=function(h,s,l)   return _hsla(h,s,l)       end,
[4]=function(h,s,l,a) return _hsla(h,s,l,a)     end
},"color.hsla() accepts 1 to 4 parameters")

end

I hope this helps :-)

Cheers,
Pierre-Yves

```