lua-users home
lua-l archive

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

Erik Cassel wrote:
However, it occurs to me that this isn't strictly necessary.  When my C++
object handles the __index request, it already knows what "self" is, because
it is passed in on the stack, along with the function name.  It is redundant
to require the object again as the first function argument.  My Lua code
could look like this:

	foo = newFoo()
	foo.prop = 2

Note that the colon syntax applies to function calls ("methods") and not assignments or index operations ("properties"). This is illegal syntax:

foo:prop = 2

That aside, I believe that you'll find you are mistaken the redundany of the self parameter as the __index metamethod only retrieves the member, but does not call it.

foo1 = newObj()
foo2 = newObj()
assert( getmetatable(foo1) == getmetatable(foo2), "huh?" )
bar1 =
bar2 =

In order for bar1 and bar2 to be different functions, you'd have to create each one using lua_pushcclosure(). In other words, each object would have to have its own set of functions instead of all objects of a class sharing a single set of functions. In fact, the typical implementation has the metatable as the __index instead of an __index function.

You _can_ do this, of course, but do you really want to? If you have a class with 5 methods, and you create 100 instances of this class, you would have to create 500 closures. You could lazily create these closures in the __index metamethod, but it's probably a bit of overhead for not much syntactical gain.