00001 ---- Copyright 2011 Simon Dales
00002 --
00003 -- This work may be distributed and/or modified under the
00004 -- conditions of the LaTeX Project Public License, either version 1.3
00005 -- of this license or (at your option) any later version.
00006 -- The latest version of this license is in
00007 -- http:
00008 --
00009 -- This work has the LPPL maintenance status `maintained'.
00010 --
00011 -- The Current Maintainer of this work is Simon Dales.
00012 --
00013
00014 --[[!
00015 \file
00016 \brief enables classes in lua
00017 ]]
00018
00019 --[[ class.lua
00020 -- Compatible with Lua 5.1 (not 5.0).
00021
00022 ---------------------
00023
00024 ]]--
00025 --! \brief ``declare'' as class
00026 --!
00027 --! use as:
00028 --! \code{lua}
00029 --! TWibble = class()
00030 --! function TWibble:init(instance)
00031 --! self.instance = instance
00032 --! -- more stuff here
00033 --! end
00034 --! \endcode
00035 --!
00036 function class(BaseClass, ClassInitialiser)
00037 local newClass = {} -- a new class newClass
00038 if not ClassInitialiser and type(BaseClass) == 'function' then
00039 ClassInitialiser = BaseClass
00040 BaseClass = nil
00041 elseif type(BaseClass) == 'table' then
00042 -- our new class is a shallow copy of the base class!
00043 for i,v in pairs(BaseClass) do
00044 newClass[i] = v
00045 end
00046 newClass._base = BaseClass
00047 end
00048 -- the class will be the metatable for all its newInstanceects,
00049 -- and they will look up their methods in it.
00050 newClass.__index = newClass
00051
00052 -- expose a constructor which can be called by <classname>(<args>)
00053 local classMetatable = {}
00054 classMetatable.__call =
00055 function(class_tbl, ...)
00056 local newInstance = {}
00057 setmetatable(newInstance,newClass)
00058 --if init then
00059 -- init(newInstance,...)
00060 if class_tbl.init then
00061 class_tbl.init(newInstance,...)
00062 else
00063 -- make sure that any stuff from the base class is initialized!
00064 if BaseClass and BaseClass.init then
00065 BaseClass.init(newInstance, ...)
00066 end
00067 end
00068 return newInstance
00069 end
00070 newClass.init = ClassInitialiser
00071 newClass.is_a =
00072 function(this, klass)
00073 local thisMetabable = getmetatable(this)
00074 while thisMetabable do
00075 if thisMetabable == klass then
00076 return true
00077 end
00078 thisMetabable = thisMetabable._base
00079 end
00080 return false
00081 end
00082 setmetatable(newClass, classMetatable)
00083 return newClass
00084 end
00085 --eof