lua-users home
lua-l archive

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


On Sun, Dec 26, 2010 at 12:32 AM, Peyman <peiman_3009@yahoo.com> wrote:
>> Learn about metatables and metamethods.
>
> there is no way instead of metatables ?

No.

> there is a simple sample of metatables ?


 -- create a new metatable
 meta = {}

 -- define a function that returns a table after giving it our metatable
 function valueset(t)
   return setmetatable(t or {}, meta)
 end

 -- add metamethods to our metatable that change behavior for + and *
 function meta.__add(set1, set2)
   local result = {}
   for i = 1, math.min(#set1, #set2) do
     result[i] = set1[i] + set2[i]
   end
   return valueset(result)
 end
 function meta.__mul(set1, set2)
   local result = {}
   for i = 1, math.min(#set1, #set2) do
     result[i] = set1[i] * set2[i]
   end
   return valueset(result)
 end

 -- test it
 a = valueset{1, 2, 3}
 b = valueset{5, 6, 7}

 c = a + b                --> {6, 8, 10}
 c = a * b                --> {5, 12, 21}


-Duncan