class

From Wake
Jump to: navigation, search

Module: class

Type: Lua

Autorequired: no
File: lib/class.lua

Creates a new class type.

Function

Synopsis

c = class()
c = class(base)

Arguments

class base

The (optional) class to derive this one from.

Returns

class c

The class object, which can be used to construct instances of the class.


Creating Classes

Creating a new class is as simple as calling the class() function. You can then define functions on that class.

local MyClass = class() -- create the class

function MyClass:foo()
  print "bar!"
end

Creating an instance of the class can be done just by calling new() on the class object.

local obj = MyClass.new()
obj:foo() -- prints "bar!"

Constructors can be defined using the special construct() function. Arguments passed when making an instance of the class will be passed to the constructor.

local MyClass = class()

function MyClass:construct(baz)
  self.baz = baz
end

function MyClass:foo()
  print(self.baz)
end

local obj = MyClass.new("bar")
obj:foo() -- prints "bar"

Generally, you define any properties in the constructor, such as self.baz in the sample above. Note that properties defined in this manor are public.

Special Functions

Every class has a few special functions defined.

class()

Returns the class object.

local obj = MyClass.new()
print(obj:class() == MyClass) -- prints true

super()

Returns the base class (see Inheritance)

instanceOf(lookingFor)

Returns true if the class is an instance of the class object passed to lookingFor.

Inheritance

Single inheritance is done by passing the parent class instance to class(). Inheritance hierarchies have no limit aside from memory and stack use.

local MyClass = class()

function MyClass:foo()
  print "bar"
end

local MyChildClass = class(MyClass)

local obj = MyChildClass.new()
obj:foo() -- prints "bar"

Overriding Functions

You can override functions simply by redefining them.

local MyClass = class()

function MyClass:foo()
  print "bar"
end

local MyChildClass = class(MyClass)

function MyChildClass:foo()
  print "baz"
end

local obj = MyChildClass.new()
obj:foo() -- prints "baz"

Calling base implementations

You can call the base implementation for a function by using the super() method and passing self to the function you are calling.

local MyClass = class()

function MyClass:foo()
  print "bar"
end

local MyChildClass = class(MyClass)

function MyChildClass:foo()
  self:super().foo(self)
  print "baz"
end

local obj = MyChildClass()
obj:foo() -- prints "bar" and "baz"

You can also use the class object in place of super() if, for example, you want to call a specific method of a specific parent class.

function MyChildClass:foo()
  MyClass.foo(self) -- equivalent to self:super().foo(self), but this could break if you change the class hierarchy
  print "baz"
end