This package provide simple object-oriented capabilities to Lua. Each class is defined with a metatable, which contains methods. Inheritance is achieved by setting metatables over metatables. An efficient type checking is provided.
localclass=require'class'-- define some dummy A classlocalA=class('A')
functionA:__init(stuff)
self.stuff=stuffendfunctionA:run()
print(self.stuff)
end-- define some dummy B class, inheriting from AlocalB=class('B', 'A')
functionB:run5()
fori=1,5doprint(self.stuff)
endend-- create some instances of both classeslocala=A('hello world from A')
localb=B('hello world from B')
-- run stuffa:run()
b:run()
b:run5()First, require the package
localclass=require'class'Note that class does not clutter the global namespace.
Class metatables are then created with class(name) or equivalently class.new(name).
localA=class('A')
localB=class('B', 'A') -- B inherit from AYou then have to fill-up the returned metatable with methods.
functionA:myMethod()
-- do somethingendThere are two special methods: new(), which already exists when the class is created and should not be overrided
and __init() which is called by new() at the creation of the class.
functionA:__init(args)
-- do something with args-- note that self existsendCreation of an instance is then achieved with the new() function or (equivalently) using the Lua __call metamethod:
locala=A('blah blah') -- an instance of Alocalaa=A.new('blah blah') -- equivalent of the aboveCreates a new class called name, which might optionally inherit from parentname.
Returns a table, in which methods should be defined.
Note that the returned table is not the metatable, but a constructor table (with a __call
function defined). In that respect, one can use the following shorthand:
localA=class.new('A')
locala=A.new() -- instance.localaa=A() -- another instance (shorthand).There is also a shorthandclass.new(), which is class().
Return a new (empty) instance of the class name. No __init method will be called.
Return the metatable (i.e. the table containing all methods) related to class name.
Return the type of the object obj (if this is a known class), or the type
returned by the standard lua type() function (if it is not known).
Check is obj is an instance (or a child) of class name. Returns a boolean.