Next: 8.8 Modules Up: 8 Some Examples Previous: 8.6 Inheritance

8.7 Programming with Classes

There are many different ways to do object-oriented programming in Lua. This section presents one possible way to implement classes, using the inheritance mechanism presented above. Please notice: the following examples only work with the index fallback redefined according to Section 8.6.

As one could expect, a good way to represent a class is as a table. This table will contain all instance methods of the class, plus eventual default values for instance variables. An instance of a class has its parent field pointing to the class, and so it ``inherits'' all methods.

For instance, a class Point can be described as in Figure 2. Function create helps the creation of new points, adding the parent field. Function move is an example of an instance method.

Point = {x = 0, y = 0}

function Point:create (o)
  o.parent = self
  return o
end

function Point:move (p)
  self.x = self.x + p.x
  self.y = self.y + p.y
end

...

--
-- creating points
--
p1 = Point:create{x = 10, y = 20}
p2 = Point:create{x = 10}  -- y will be inherited until it is set

--
-- example of a method invocation
--
p1:move(p2)
Finally, a subclass can be created as a new table, with the parent field pointing to its superclass. It is interesting to notice how the use of self in method create allows this method to work properly even when inherited by a subclass. As usual, a subclass may overwrite any inherited method with its own version.


Next: 8.8 Modules Up: 8 Some Examples Previous: 8.6 Inheritance