[Date Prev][Date Next][Thread Prev][Thread Next]
[Date Index]
[Thread Index]
- Subject: Re: OOP and modules
- From: Tomas <tomas@...>
- Date: Sun, 12 Mar 2006 23:04:12 -0300 (BRT)
Hi David
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
You could omit the _M (but then you'll have to write the implicit
`self'):
function new (self, name, transitionRecord)
...
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?
I think there is nothing wrong with your implementation.
I would like to add that if you want some inheritance, you could
use the second argument of `module()' to achieve an elegant solution.
Let's define a basic object class:
local setmetatable = setmetatable
module"obj"
function inherit (self)
return function (newclass)
setmetatable (newclass, self)
self.__index = self
return newclass
end
end
function new (self, o)
o = o or {}
setmetatable (o, self)
self.__index = self
return o
end
Now you can define a new class which extends the previous `obj':
local obj = require"obj"
module ("myobj", obj:inherit())
Class `myobj' will "inherit" the methods `new' and `inherit'
from class `obj'.
Tomas