[Date Prev][Date Next][Thread Prev][Thread Next]
[Date Index]
[Thread Index]
- Subject: Re: do some operation on a set of values
- From: Steve Litt <slitt@...>
- Date: Sat, 25 Dec 2010 23:15:07 -0500
On Saturday 25 December 2010 21:52:44 Duncan Cross wrote:
> 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
Thanks Duncan,
I have only a week or two of Lua and had been putting off metatables because
they seemed hard to explain. Your example plus the info on
http://lua-users.org/wiki/MetamethodsTutorial
have given me at least some idea of how metatables and metamethods can be used
to overload arithmetic operators in Lua.
So you sped up my learning by several days. Thanks!
SteveT
Steve Litt
Recession Relief Package
http://www.recession-relief.US
Twitter: http://www.twitter.com/stevelitt