wattageTileEngineDocs

Lua Object-Oriented Programming (OOP) Primer

Overview

There are a number of ways to practice OOP in Lua, and a quick internet
search will reveal them. This document focuses on the approach
utilized by the internal components of the Wattage Tile Engine, which
uses closures. Although it is not necessary to use OOP in order
to use the Wattage Tile Engine, it is necessary to understand these
concepts in order to use the optional ObjectSystem which this library
exposes. For more information on the ObjectSystem, please see the
ObjectSystem Usage Guide.

This guide will show how the following can be implemented using the
closure approach for OOP.

Class Definition

Each class exposes a new() function which acts as a constructor and
creates the closure. The new function will create an instance and
return that instance. In the following example, that instance is
called “self”…

-- Create the table for the class definitionlocalEmptyClassDefinition={}-- Define the new() functionEmptyClassDefinition.new=function()localself={}returnselfend

Public Properties

Public properties can be created by declaring them on “self”. See
the example below…

Private Functions

Private functions can be created by declaring local functions within
the closure. These private functions would be in scope within public
functions but not outside the closure. See the following example…

localExampleClass={}ExampleClass.new=function()localself={}localfunctionprivateFunction()print("Inside Private Function")endfunctionself.publicFunction()print("Inside Public and Calling Private")privateFunction()endreturnselfendlocalinstance=ExampleClass.new()-- Prints the following...-- "Inside Public and Calling Private"-- "Inside Private Function"instance.publicFunction()-- This results in an error...instance.privateFunction()

Static Functions

A static function can be created by declaring it on the class definition
table. See the following example…

Function Overriding

A class may override a function on its parent class by overwriting the
function reference on “self”. A call to the parent class implementation
can be facilitated by making a private copy of the parent implementation
before overriding it. See ExtendingClass1 and ExtendingClass2 in the
example below…