Protocol for Using Classes


A class is made from a Lua table using a special protocol (see Creating Classes). This topic gives an overview of the syntax you use to work with the class in MX Script. The details are given in the Creating Classes topic.

To begin using a class, you must instantiate it—that is, you must create an instance of the class. An instance of a class is an object that exists in memory and is independent of other instances of the same class and other classes. In MX Script, a common interface exists for the creation, destruction, and use of classes. In the table below, we show how to manage a hypothetical class named CMyClass. In an actual script, CMyClass might be CImage class, CRect class, CTextView, another MX Script class, or a class that you create.

To use a class in Lua, there is a standard progression of operations:

    Include the class definition

    Create an instance

    Use the class

    Delete the class

These operations follow a similar work flow in your scripts, as detailed in the table below.

Protocol for Working with a Class, "CMyClass"

To Create an Instance:

(the Constructor)

C = CMyClass:new()

    C is returned as a reference to a new instance of the class CMyClass.

    The () may contain optional parameters.

To Destroy an Instance:

(the Destructor)

C = CMyClass:delete()

    C is an existing reference to an instance of the class CMyClass.

    The () never contains parameters.

To use class methods or data:

value = C:Method() (returns a value)

C:Method() (returns nothing)

value = C.Data (Data is a value)

    Method is a "function" inside CMyClass.

    Data is a property (a value) inside CMyClass.

 

A Class contains both Methods ("functions") and Properties (data, or "variables"). Notice in the table above that we use both . (dot) and : (colon) operators to access the class members. This is described in Creating Classes.

To view a simple example using the methods described above, see Creating a Simple Script.

Related Topics

Creating Classes

Script Classes

Naming Conventions

Creating a Simple Script