[Date Prev][Date Next][Thread Prev][Thread Next]
[Date Index]
[Thread Index]
- Subject: Re: RES: RES: Cryptic OOP syntax
- From: Mark Hamburg <mhamburg@...>
- Date: Tue, 01 Feb 2005 08:14:42 -0800
Lua actually has most of what one needs to build OOP systems -- particularly
if one ignores encapsulation enforcement.
It's pretty easy to build a function that will do something like the
following:
Foo = class "Foo" {
init = function( self, name )
self._name = name
end,
hello = function( self )
print( "Hello from " .. tostring( self:name() ) )
end,
name = function( self )
return self._name
end
}
joe = Foo.new( "Joe" )
bob = Foo.new( "Bob" )
joe:hello()
bob:hello()
One thing that might make that a little nicer syntactically would be if
Lua's table constructors would recognize named functions and named methods
-- i.e.
function f( ... ) end
would be the same as:
f = function( ... ) end
and
function :f( ... ) end
would be the same as:
f = function( self, ... ) end
It is easy to provide inheritance from other classes along the following
lines:
Baz = class "Baz" {
Foo,
hello = function( self )
print( "Greetings from " .. tostring( self:name() ) )
end
}
What is tricky are calls to the hidden methods. A variety of approaches can
be used with various performance characteristics and syntactical efforts to
use them.
If you are prepared to give the methods a special function environment, you
can even make it reasonably transparent -- e.g.:
Super.method( self, ... )
This would be easier to implement if Lua provided a way to duplicate a
function so that one could set a different function environment on it.
Finally, while not a problem per se, one issue that causes problems for
inexperienced users is that both obj.f() and obj:f() are valid Lua
expressions. I don't think one can change that, but a mechanism such as a
__methods metatable that is only searched by the colon operator would cause
bugs of this form to be caught more rapidly at runtime.
Hmmm... I'm sensing a set of minor proposals for enhancing Lua's OOP support
here -- or rather Lua's support for building OOP implementations:
1. Some minor enhancements to table construction syntax for function-valued
elements.
2. A way to duplicate functions so that the same function can be given
different environments. (This might take the form of a general shallow-copy
routine.)
3. A __methods metatable. This would allow some errors to be caught earlier.
It also makes it easier to implement property/attribute syntax support for
objects without slowing down method dispatch.
I've written an implementation of the last and there's an implementation on
the Wiki. Any serious proposal should, however, go through a reasonably
careful analysis of how it works in conjunction with other meta-mechanisms,
how inheritance works, etc..
Mark