lua-users home
lua-l archive

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


On 8/30/07, Michal Kolodziejczyk <> wrote:
I woul like to write some classes (to get some OO and inheritance),
which could also be modules (to get autoload and "dotted" names
notation). What is the way to accomplish it?

I would like to have something like this:

--- class/class1.lua ---
local Object=Object
module('class.class1', subclassOf(Object))

You answered your own question here.

  function constructor(self) print("I am a class1 ctr") end

Is it possible to implement something like this in pure lua? Where
should I start? Should I redefine module/require, or is there another
way? I could do it if module(name, func1, ...) could call func1 with a
parameter (e.g. parent class) or with "self", but it cannot.

subclassOf can return a function that closes over the value of the superclass. Lua's module will then call this function passing the module (i.e. the new class). This is all you need to tie the two together...

Or you can just not bother with inheritance, and do any code reusing by composition... inheritance is overrated in a dynamic language. Just have an "is_object" function that module calls and sets up a proper new method for you, and creates a method table that you fill:

module("myclass", is_object)

-- class methods are in the top level
function class_method(...)

-- new creates a fresh instance (an empty table), ties it with
-- the instance methods table and calls this
function instance_methods:initialize(...)
  -- self here is an instance

-- Instance methods go inside the "instance_methods" table
function instance_methods:foo(...)
  -- self here is an instance

If you need code reuse then implementing some kind of mixins or traits can also be useful, check the literature on that.


Fabio Mascarenhas