lua-users home
lua-l archive

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



Hi list,

I've been converting some code to a proper package structure. Since it's still 5.0.2 code, I'm using the compat-5.1 code which has been working beautifully.

Previously, when defining a class, I would do something like this:

ParseTree = {}

function ParseTree:new(name, transitionRecord)
   local o = {}

   setmetatable(o, self)
   self.__index = self

   return o
end

which is, IIRC, the technique given in PIL to implement classes.

But with modules, this all becomes tedious. I'd have to do something like:

require ("clip.parsetree")
parsetree = clip.parsetree.ParseTree:new()

which seems a bit excessive to me.

My solution is to do the following:

module ("clip.parsetree")

function _M:new(name, transitionRecord)
assert( self == _M, format("You need to call %s:new(), not %s.new()!", _NAME, _NAME ) )

   -- normal stuff follows as above...
end


This seems to work, and I can now do:
require ("clip.parsetree")
parsetree = clip.parsetree:new()

which is what I wanted.

Is this the "right" way of implementing classes in modules? Is there a better way? Is there something wrong with this approach that I should be aware of?

Thanks much.
Best,
David

--
~David-Haley
http://david.the-haleys.org