[Date Prev][Date Next][Thread Prev][Thread Next]
[Date Index]
[Thread Index]
- Subject: Re: Question about __index and classes
- From: Lorenzo Donati <lorenzodonatibz@...>
- Date: Sun, 28 Aug 2011 02:39:12 +0200
On 28/08/2011 0.52, Michael Kirsch wrote:
There is something I don't understand about the way __index and
metamethods work. The way I understand, the "." operator looks in the
table itself and the ":" operator looks directly in the metatable. If
so, then why is it necessary to say:
MyClass.__index = MyClass
for you to be able to use ":"?
If ":" looks right in the metatable, then it shouldn't be needed. To
me it seems like what it would do is let you call metamethods using
the "." operator, but it doesn't work that way for some reason.
I won't repeat what others have correctly said about "." and ":".
As for your doubt regarding:
MyClass.__index = MyClass -- (*)
this is only an idiom for certain OO approaches.
In this approach you model a class as a table:
MyClass = {}
then add methods to it:
function MyClass.Method1( self, arg1, arg2 )
...
end
Then you create objects as tables having MyClass as metatable:
obj1 = setmetatable( {}, MyClass )
the problem is that for this syntax to work:
obj1:Method1( 'foo', 'bar' )
which is completely equivalent to:
obj1.Method1( obj1, 'foo', 'bar' ) -- (1)
Method1 must be retrieved and called. From (1) is evident that the
lookup is done in obj1, but obj1 hasn't got such a key.
Metatable magic begins here: when the lookup for Method1 in (1) fails,
Lua notices that obj1 has MyClass as metatable. Then searches the
metatable for a specially named key: __index
If MyClass has such a key and that key points to a table, then the
lookup in (1) (which failed) will be redone in the table pointed to by
__index.
That table could be ANY table, but it is idiomatic to make it point to
MyClass using (*), so that the lookup will find a key named "Method1"
and perform the call in (1) using the function pointed to by Method1.
Remember that Lua has no notion of function names; function in Lua are
first class values; "Method1" is not the name of a function inside
"MyClass", but it is the name of a key whose value happens to be a
function.
Moreover, bear in mind that setting a metatable on a table, doesn't make
it automatically an object of some class.
The OO terminology is a useful abstraction over all this stuff, but
remember that Lua has no "true classes" and this is only one of the many
approaches to OO [1].
Hope this helps.
[1] http://lua-users.org/wiki/ObjectOrientedProgramming
-- Lorenzo