lua-users home
lua-l archive

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


On Sun, Dec 26, 2010 at 02:32:10AM +0200, Peyman wrote:
> > Learn about metatables and metamethods.
> 
> there is no way instead of metatables ? i cant understand metatables.
> there is a simple sample of metatables ?

It's legal to say  a+b  if a and b are numbers.
It's illegal to say  a+b  if a and b are tables.
But you would like to.

Now Lua says: "OK, I'll allow you to say  a+b  for some tables, not
all, provided that you please write for me a function, called say 
add_termwise(a,b), that takes two of those tables a and b and returns 
whatever you would like their sum to be.  Then I will tell you a way to 
let  a+b  mean the same as add_termwise(a,b)."

So you write something like:

add_termwise = 
    function(a,b) local c={} 
        for i=1,min(#a,#b) do c[i]=a[i]+b[i] 
        end 
        return c 
    end

and you come back and say: "OK, dear Lua, I have done as you say.
now what?"  And Lua says:

"Say  setmetatable(a,{__add=add_termwise})  and then you can do
a+b  or  b+a  the way you want to, even if b is just any old table."

And you try it, and it works, but then you complain "Dear Lua, it 
seems to work only for a+b, not for b+c."  And Lua says: "Sorry,
but I told you it does not work for all tables.  Here's an idea:
instead of defining this addition for some nondescript name like
'a', do it for a table called 'Vector'.  Now, when you want an 
array b to allow addition, you say: 
    setmetatable(b,getmetatable(Vector))

"That's a lot of typing, dear Lua," you say.  And Lua, ever helpful,
says: "If you do this:

getmetatable(Vector)['__call'] = function(self,a) local c={} 
    setmetatable(c,getmetatable(self))
    for i=1,#a do c[i]=a[i] end
    return c
    end

you can from now on say  b=Vector{1,2,3}  when you want to make
a new Vector.

And you say, "Yes dear Lua, I have done these things, and can see 
that they work, but why?"

And Lua, ever patient says: "You know, there is a very nice book 
called 'Programming in Lua', available on the Internet if you
can't wait to receive the latest version by mail, by no less than
Roberto Ierusalimschy himself, that explains these things very
nicely."

Hope this helps.

Dirk