lua-users home
lua-l archive

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



On Jan 25, 2005, at 19:49, Mark Hamburg wrote:

Function closures
-----------------
This is covered in Programming in Lua. Since a function can reference
upvalues and clients can't look inside without using the debug interface -- and in any context where encapsulation mattered, one should probably remove the debug interface. The chief downside is that construction and usage don't have much in common with other approaches to implementing objects in Lua.

One thing that I like with this approach is that, beside providing encapsulation, it provides, er, "visual encapsulation". In other words, the entire object is defined inside one function. This is pretty neat :)

For example:

// Root class

function LUObject()
    local self = {}

    local description = function()
	    print "default description method"
    end

    return
    {
	    description = description
    }, self
end

// A subclass

function MySubclass()
    local self, super = LUObject();

    local description = function()
	    print "my very own description as well"
	    super.description()
    end

    return
    {
	    description = description
    }, self
end

And finally:

anObject = MySubclass()
anObject.description()

As an added deviance, if you wanted to make a class <gasp> "final" </gasp>, you would not return "self" at the end of an "object" function... scary thought :o)

Would the above scheme provide both inheritance and encapsulation without too much fuss?

Cheers

--
PA
http://alt.textdrive.com/