[Date Prev][Date Next][Thread Prev][Thread Next]
[Date Index]
[Thread Index]
- Subject: RE: [Qs (a bit bent, I admit)] regarding the behaviour of non sta ndar d contents of a metatable
- From: Benoit Germain <bgermain@...>
- Date: Fri, 20 Sep 2002 17:24:22 +0200
> -----Original Message-----
> From: Roberto Ierusalimschy [mailto:roberto@inf.puc-rio.br]
> Sent: vendredi 20 septembre 2002 16:55
> To: Multiple recipients of list
> Subject: Re: [Qs (a bit bent, I admit)] regarding the behaviour of non
> standar d contents of a metatable
>
>
> > I was wondering: what misbehaviours I should expect if I set non
> > event-related fields of a metatable ?
>
> The metatable is a regular table, and can be used for any mean.
>
>
> > Is this endorsed by the language and will work as it should
> be expected
> > from any table, or is there some problem regarding a
> special handling of
> > metatables I am not aware of ?
>
> Such use is completely "legal". The only small implementation
> detail is
> that Lua assumes that metatables do not change very
> frequently. If they
> do, some metatable tests (basically when accessing a table with that
> metatable but without an __index field) may slow down a bit.
>
That's ok, since the non-event fields will remain in place even if their
value will change. No other fields should be created/destroyed either once
the metatable is built.
>
> > setmetatable(bob,t1)
> > [...]
> > Since bob is a table and field b does not exist, __gettable get its
> > metatable t1. Since t1 is non-nil and not a function,
> __gettable tries to
> > get t1[b], which should yield 2.
>
> Not so fast. "bob.b" will try to index the __index field in
> the metatable,
> not the metatable itself! So, your example should read
>
> setmetatable(bob,{__index=t1})
>
>
But t1 is bob's metatable, and t1 already has an __index field. doing this
would set bob's metatable as {__index = { __index = { a = 1 } } } ?
I think what I should do it set the metatable of { a = 1 } to { __index = t2
} :
> ti1 = {a=1}
> ti2 = {b=2}
> mt1={__index=ti1}
> mt2={__index=ti2}
> bob={c=3}
> setmetatable(bob,mt1)
> setmetatable(ti1,mt2)
> print (bob.a)
1
> print (bob.b)
2
> print (bob.c)
3
here we go :-)
> -- Roberto
>