lua-users home
lua-l archive

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


On Wed, 24 Feb 2010 08:48:55 +0100
Eike Decker <zet23t@googlemail.com> wrote:

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

This is very handy trick, indeed. But I don't understand the advantage of using metatables as type identifiers. Wouldn't any attribute do the job? For instance:

> 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 rgb(r,g,b) return {r,g,b, type=rgbtype) end
function hsl(h,s,l) return {h,s,l, type=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

local t = c.type

> 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).

Yes, thank you.

> Cheers,
> Eike
>

Denis
________________________________

la vita e estrany

http://spir.wikidot.com/