lua-users home
lua-l archive

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


-----BEGIN PGP SIGNED MESSAGE-----
Hash: SHA1

Grellier, Thierry wrote:
[...]
> function C:new( o )
[...]
> function D:m()
> 
>   C.m( self )    -- no better OO-like syntax available ? like :C:m() for
> example ?
[...]

It very much depends on your OO system. Most Lua OO systems don't
support any kind of 'super' syntax, because when an object is created
they typically copy all methods from all superclasses into a single
table in order to speed up method dispatch.

Your OO system appears to be trying to maintain the superclass chain, as
far as I can tell --- this will work, and will allow you to do
superclass calls, but will make method dispatch much slower (because the
system will need to do a table lookup at every level in the class
hierarchy). I also suspect there's a bug in your C:new() function;
"self.__index = self" isn't going to do anything terribly useful.

One of the drawbacks of Lua's roll-your-own OO system is that it's a bit
hard to get your head around at first.

The OO system I tend to use is based on the following function:

- ---snip---
function Class(...)
        local c = {}

        for _, base in ipairs(arg) do
                for i, j in pairs(base) do
                        c[i] = j
                end
        end

        c.__index = c
        function c.new(...)
                local o = {}
                setmetatable(o, c)
                o:_init(unpack(arg))
                return o
        end

        return c
end
- ---snip---

Calling Class() creates a class, subclassing zero or more other classes
if required. This would make your code:

- --snip---
C = Class()
function C:m()
    print "C:m()"
end

D = Class(C)
function D:m()
    C.m(self) -- no syntactic sugar here
    print "D:m()"
end

d = D.new() -- note use of . and not :
d:m()
- ---snip--

(Untested. There may be bugs.)

One day I'm going to make a page in the Wiki collecting all the various
OO systems people have come up with and comparing them...

- --
+- David Given --McQ-+
|  dg@cowlark.com    | "Those that repeat truisms, are also forced to
| (dg@tao-group.com) | repeat them." --- Anonymous from Slashdot
+- www.cowlark.com --+
-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.4.1 (GNU/Linux)
Comment: Using GnuPG with Mozilla - http://enigmail.mozdev.org

iD8DBQFESLAuf9E0noFvlzgRAo/IAKDfRzr8KnqzuuGCPspLkCsySJUdkwCaA3L8
rTLQnTvMNZsp++5e/bvT7Zc=
=Fn13
-----END PGP SIGNATURE-----