lua-users home
lua-l archive

Re: do some operation on a set of values

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


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

AltStyle によって変換されたページ (->オリジナル) /