1 ---- Copyright 2011 Simon Dales
3 -- This work may be distributed and/or modified under the
4 -- conditions of the LaTeX Project Public License, either version 1.3
5 -- of
this license or (at your option) any later version.
6 -- The latest version of
this license is in
9 -- This work has the LPPL maintenance status `maintained
'.
11 -- The Current Maintainer of this work is Simon Dales.
16 \brief enables classes in lua
20 -- Compatible with Lua 5.1 (not 5.0).
25 --! \brief ``declare'' as class
30 --! function TWibble.init(instance)
31 --! self.instance = instance
32 --! -- more stuff here
36 function class(BaseClass, ClassInitialiser)
37 local newClass = {} -- a new class newClass
38 if not ClassInitialiser and type(BaseClass) == 'function' then
39 ClassInitialiser = BaseClass
41 elseif type(BaseClass) == 'table
' then
42 -- our new class is a shallow copy of the base class!
43 for i,v in pairs(BaseClass) do
46 newClass._base = BaseClass
48 -- the class will be the metatable for all its newInstanceects,
49 -- and they will look up their methods in it.
50 newClass.__index = newClass
52 -- expose a constructor which can be called by <classname>(<args>)
53 local classMetatable = {}
54 classMetatable.__call =
55 function(class_tbl, ...)
56 local newInstance = {}
57 setmetatable(newInstance,newClass)
59 -- init(newInstance,...)
60 if class_tbl.init then
61 class_tbl.init(newInstance,...)
63 -- make sure that any stuff from the base class is initialized!
64 if BaseClass and BaseClass.init then
65 BaseClass.init(newInstance, ...)
70 newClass.init = ClassInitialiser
73 local thisMetabable = getmetatable(this)
74 while thisMetabable do
75 if thisMetabable == klass then
78 thisMetabable = thisMetabable._base
82 setmetatable(newClass, classMetatable)