lua-users home
lua-l archive

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


Forgive me if this is already known to the more experienced of you,
But in light of all the oop talk and lua, I thought at the risk of
repetition I'd share the really quick, simple and intuitive oop stuff I've
devised for my app.

Just define a bunch of tables, that work as classes.  They can of course
have whatever methods (functions) and fields (variables).

For example:

Vehicle = 
{ 
   -- whatever fields you want
   -- whatever functions you want
}

Engine = 
{
   -- whatever fields you want
   -- whatever functions you want
}

Wheels =
{
   -- whatever fields you want
   -- whatever functions you want
}

Wings = 
{
   -- whatever fields you want
   -- whatever functions you want
}

// and we'll want types to instantiate that inherit from the above "classes"

Car =
{
   -- whatever fields you want
   -- whatever functions you want
}

Plane =
{
   -- whatever fields you want
   -- whatever functions you want
}

CarMetatable =
{
__newindex = function(table, key)
    return rawget(Vehicle, key) or  -- "inherit from Vehicle"
    return rawget(Engine, key) or   -- "inhereit from Engine"
    return rawget(Wheels, key) end  -- "inherent from Wheels"
}

PlaneMetatable =
{
__newindex = function(table, key)
    return rawget(Vehicle, key) or  -- "inherit from Vehicle"
    return rawget(Engine, key) or   -- "inhereit from Engine"
    return rawget(Wings, key) end  -- "inherent from Wings"
}

setmetatable(Car, CarMetatable)
setmetatable(Plane, PlaneMetatable)

This only deals with the inheritance aspect and not instantiation of
objects, and there are other ramifications to contend with, but it sure does
make inheriting from other "objects" very intuitive and easy...

Ando