lua-users home
lua-l archive

[Date Prev][Date Next][Thread Prev][Thread Next] [Date Index] [Thread Index]


On Tue, Feb 23, 2010 at 12:50 PM, spir <denis.spir@free.fr> wrote:
> A Color constructor needs to accept as argument an HLS, an RGB, xor a hex ("#FF0000") color format. While the latter is indeed a string, HLS and RGB formats are tables, so that I cannot distinguish using types. (This is not limited to constructors, of course.)
>
> The only solution I found is requiring the arg itself be passed inside a table:
>   c = Color{RGB={100,0,0}}
> Well, a bit heavy (but not that much heavier as typical c = Color(RGB=(100,0,0)) in other languages ;-)
>
> A side advantage is additional attributes can be set on the color at the same time:
>   RED = Color{RGB={100,0,0}, name="red"}
> But I would like to know if you use other solutions.
   Here are a couple other solutions:

Use a table literal with some string keys:
   RED = {100, 0, 0, type="rgb", name="red"}

Kind of Erlang-ish:
   RED = {"rgb", 100, 0, 0}

Use a constructor function with keyword arguments:
   RED = RGB{100, 0, 0, name="red"}

> PS: What about named args in Lua? After all, an arg list is a kind of table...
   To expand on what Petite Abeille said, there is syntactic sugar for
this. If you call a function as f { list, of, args } rather than f
(list, of, args), it's passed a single argument of a table with the
arguments.

"f { val1, val2, namedarg1=val3, namedarg2=val4 }" is the same as
"f( { val1, val2, namedarg1=val3, namedarg2=val4 } )". You can omit
the parens there, and table literals can use keys. (Any keyword
arguments with defaults can just be specified as "t.name = t.name or
default_value".) You can also omit the parens when the only argument
is a literal string.

Scott