[Date Prev][Date Next][Thread Prev][Thread Next]
[Date Index]
[Thread Index]
- Subject: Re: do some operation on a set of values
- From: Peyman <peiman_3009@...>
- Date: Sat, 25 Dec 2010 22:15:21 -0800 (PST)
--- On Sat, 12/25/10, Duncan Cross <duncan.cross@gmail.com> wrote:
> From: Duncan Cross <duncan.cross@gmail.com>
> Subject: Re: do some operation on a set of values
> To: "Lua mailing list" <lua-l@lists.lua.org>
> Date: Saturday, December 25, 2010, 8:52 PM
>
> -- 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 very very useful, i read Metamethods Tutorial in lua wiki and find out metatable is very interesting and amazing.
i think simple example like these must be in the lua manual in future but anyway thanks again.
Peyman.