lua-users home
lua-l archive

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


another possibility is to use "types" through using metatables to
identify certain tables

----
rgbtype = {}
hlstype = {}
function rgb(r,g,b) return setmetatable({r,g,b},rgbtype) end
function hsl(h,s,l) return setmetatable({h,s,l},hsltype) end

function color (c)
  local t = getmetatable(c)
  if t == rgbtype then print "rgb"
  elseif t == hlstype then print "hls"
  else print "raw"
  end
end

color(rgb(4,5,6)) -- rgb
color(0xff3333) -- raw
color(hsl(0,0,5)) -- hls

----

The metatable is carried along with the tables and identify the types
of the tables.
If you do not wish to use if ... elseif ... end structures in your
functions, you can also write a wrapping function that distincts
between metatable types in such manner:

---

function polyfunc(t)
  return function (self,...)
    local tp = getmetatable(self) or 1
    return t[tp](self,...)
  end
end

color = polyfunc {
  function (c) print "raw" end,
  rgbtype = function (c) print "rgb" end,
  hsltype = function (c) print "hsl" end
}

color(rgb(0,5,5)) -- rgb
----

Though it won't really get shorter that way (after all, it's 3
different codepaths).

Cheers,
Eike

2010/2/23 Klaus Ripke <paul-lua@malete.org>:
> On Tue, Feb 23, 2010 at 06:59:35PM +0100, Petite Abeille wrote:
>>
>> On Feb 23, 2010, at 6:50 PM, spir wrote:
>>
>> > PS: What about named args in Lua? After all, an arg list is a kind of table...
>>
>> "named args" in Lua are tables
>
> long answer: you use a table as the single parameter.
>
> You can omit the () when calling a function with a table constructor,
> so it looks almost like a plain call
>
> somefunc{'foo', 'bar', baz = 42}
>