Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Lua Object-Oriented Programming

Lua Object-Oriented Programming

Object Oriented Programming (OOP) is a very popular computer programming paradigm that designs applications by creating and manipulating objects.

The following programming languages all support object-oriented programming:

Lua is a lightweight scripting language. Although it does not have powerful built-in object-oriented (OO) features like Java or C++, it is very flexible and can implement object-oriented programming through some techniques.


Object-oriented features


Object-oriented programming in Lua

As we know, an object consists of attributes and methods.

Classes in Lua can be simulated through table + function.

As for inheritance, it can be simulated through metetable (not recommended; simulating only the most basic objects is enough for most implementations).

In Lua, the most basic structure is the table, and we can use tables to create objects.

ClassName = {}  -- 创建一个表作为类

Create objects through the new method (or another name) and initialize the object's attributes.


function ClassName:new(...)
    local obj = {}  -- 创建一个新的空表作为对象
    setmetatable(obj, self)  -- 设置元表,使对象继承类的方法
    self.__index = self  -- 设置索引元方法
    -- Initialize object properties
    obj:init(...)  -- 可选:调用初始化函数
    return obj
end

The table is the most basic composite data type in Lua and can be used to represent an object's attributes.

The function in Lua can be used to represent methods:


function ClassName:sayHello()
    print("Hello, my name is " .. self.name)
end

Use the new method to create objects, and call the class's methods through the object.


local obj = ClassName:new("Alice")  -- 创建对象
obj:sayHello()  -- 调用对象的方法

In Lua, a table can be viewed as a variant of an object. Like an object, a table has state (member variables) and can represent an independent entity.

A table not only has data members, but can also contain member functions similar to object methods:

Example

-- define the Person class

Person

=

{

name

=

""

,

age

=

0

}

-- the constructor of Person

function

Person

:

new

(

name

,

age

)

   

local

obj

=

{

}

 

-- create a new table as the object

   

setmetatable

(

obj

,

self

)

 

-- set the metatable to make it an instance of Person

    self

.

__index

=

self  

-- set the index metamethod to point to Person

    obj

.

name

=

name

    obj

.

age

=

age

   

return

obj

end

-- add a method: print personal information

function

Person

:

introduce

(

)

   

print

(

"My name is "

..

self

.

name

..

" and I am "

..

self

.

age

..

" years old."

)

end

Code explanation:

Calling the method:

-- 创建一个 Person 对象
local person1 = Person:new("Alice", 30)

-- Call the object's method
person1:introduce()  -- 输出 "My name is Alice and I am 30 years old."

A simple example

The following simple class contains three attributes: area, length, and breadth. The printArea method is used to print the calculation result:

Example

-- define the Rectangle class

Rectangle

=

{

area

=

0

,

length

=

0

,

breadth

=

0

}

-- the constructor for creating a Rectangle object

function

Rectangle

:

new

(

o

,

length

,

breadth

)

  o

=

o

or

{

}

 

-- if no object is passed, create a new empty table

 

setmetatable

(

o

,

self

)

 

-- set the metatable so that it inherits the methods of Rectangle

  self

.

__index

=

self  

-- ensure that methods and attributes can be found when accessed

  o

.

length

=

length

or

0

 

-- set the length, default is 0

  o

.

breadth

=

breadth

or

0

 

-- set the width, default is 0

  o

.

area

=

o

.

length

o

.

breadth  

-- calculate the area

 

return

o

end

-- print the area of the rectangle

function

Rectangle

:

printArea

(

)

 

print

(

"The area of the rectangle is "

,

self

.

area

)

end

Creating objects

Creating an object is the process of allocating memory for an instance of a class. Each class has its own memory and shares common data:


r = Rectangle:new(nil,10,20)

Accessing Attributes

We can use the dot . to access a class's attributes:


print(r.length)

Access member functions

We can use the colon : to access a class's member functions:


r:printArea()

Memory is allocated when the object is initialized.

Complete example

The following demonstrates a complete example of Lua object-oriented programming:

Example

-- define the Rectangle class

Rectangle

=

{

area

=

0

,

length

=

0

,

breadth

=

0

}

-- the constructor for creating a Rectangle object

function

Rectangle

:

new

(

o

,

length

,

breadth

)

  o

=

o

or

{

}

 

-- if no object is passed, create a new empty table

 

setmetatable

(

o

,

self

)

 

-- set the metatable so that it inherits the methods of Rectangle

  self

.

__index

=

self  

-- ensure that methods and attributes can be found when accessed

  o

.

length

=

length

or

0

 

-- set the length, default is 0

  o

.

breadth

=

breadth

or

0

 

-- set the width, default is 0

  o

.

area

=

o

.

length

o

.

breadth  

-- calculate the area

 

return

o

end

-- print the area of the rectangle

function

Rectangle

:

printArea

(

)

 

print

(

"The area of the rectangle is "

,

self

.

area

)

end

-- run the example:

local

rect1

=

Rectangle

:

new

(

nil

,

5

,

10

)

 

-- create a rectangle with length 5 and width 10

rect1

:

printArea

(

)

 

-- output "The area of the rectangle is 50"

local

rect2

=

Rectangle

:

new

(

nil

,

7

,

3

)

 

-- create a rectangle with length 7 and width 3

rect2

:

printArea

(

)

 

-- output "The area of the rectangle is 21"

Running the above program, the output is:


矩形面积为      50
矩形面积为      21

Lua Inheritance

Inheritance means that one object directly uses the attributes and methods of another object. It can be used to extend the attributes and methods of a base class.

Inheritance in Lua is implemented by setting the metatable of the subclass.

We can create a new table and set its metatable to the parent class.

In the following example, the Square class inherits the attributes and methods of the Rectangle class and makes changes based on them.

-- define the Rectangle class

Rectangle

=

{

area

=

0

,

length

=

0

,

breadth

=

0

}

-- the constructor for creating a Rectangle object

function

Rectangle

:

new

(

o

,

length

,

breadth

)

  o

=

o

or

{

}

 

-- if no object is passed, create a new empty table

 

setmetatable

(

o

,

self

)

 

-- set the metatable so that it inherits the methods of Rectangle

  self

.

__index

=

self  

-- ensure that methods and attributes can be found when accessed

  o

.

length

=

length

or

0

 

-- set the length, default is 0

  o

.

breadth

=

breadth

or

0

 

-- set the width, default is 0

  o

.

area

=

o

.

length

o

.

breadth  

-- calculate the area

 

return

o

end

-- print the area of the rectangle

function

Rectangle

:

printArea

(

)

 

print

(

"The area of the rectangle is "

,

self

.

area

)

end

-- define the Square class, inheriting from the Rectangle class

Square

=

Rectangle

:

new

(

)

 

-- Square inherits from the Rectangle class

-- override the constructor (a square has equal side lengths)

function

Square

:

new

(

o

,

side

)

  o

=

o

or

{

}

 

-- if no object is passed, create a new empty table

 

setmetatable

(

o

,

self

)

 

-- set the metatable so that it inherits the methods of Rectangle

  self

.

__index

=

self  

-- ensure that methods and attributes can be found when accessed

  o

.

length

=

side

or

0

 

-- set the side length

  o

.

breadth

=

side

or

0

 

-- the width and length of a square are equal

  o

.

area

=

o

.

length

o

.

breadth  

-- calculate the area

 

return

o

end

-- run the example:

local

rect

=

Rectangle

:

new

(

nil

,

5

,

10

)

 

-- create a rectangle with length 5 and width 10

rect

:

printArea

(

)

 

-- output "The area of the rectangle is 50"

local

square

=

Square

:

new

(

nil

,

4

)

 

-- create a square with side length 4

square

:

printArea

(

)

 

-- output "The area of the rectangle is 16"

Rectangle class: is still the basic class of rectangle, having length、breadth and area attributes, as well as methods to calculate and print the area.

Square The class inherits from Rectangle:Square The class through Rectangle:new() to inherit Rectangle class's methods and attributes. Since the length and width of a square are equal, we Square:new overrode the constructor in the method, setting length and breadth to the same value (i.e. side)。

Override constructor:Square:new(o, side) When the method creates a Square object, it uses the passed side length side Initialization length and breadth attribute and calculates the area.

Running result:


矩形面积为  50
矩形面积为  16

Function overriding

In Lua, function overriding (also called method overriding) refers to the redefinition or replacement of an existing method in a parent class by a subclass during inheritance.

A subclass can modify or extend the method behavior of the parent class as needed.

In the above example, the Square class overrides the constructor of the Rectangle class, thereby changing the way the object is initialized. In particular, it sets the rectangle's length and breadth to the same value, because the characteristic of a square is that all sides are equal.

Next, we show how to override methods through an Animal class and a Dog class that inherits from it.

-- define the Animal class

Animal

=

{

name

=

"Unknown"

}

-- Constructor of the Animal class

function

Animal

:

new

(

o

,

name

)

  o

=

o

or

{

}

 

-- If no object is passed in, create a new empty table

 

setmetatable

(

o

,

self

)

 

-- Set the metatable so that it inherits Animal's methods

  self

.

__index

=

self  

-- Allow the object to access Animal's methods

  o

.

name

=

name

or

"Unknown"

 

-- Set the name, defaulting to "Unknown"

 

return

o

end

-- Method of the Animal class: the sound it makes

function

Animal

:

speak

(

)

 

print

(

self

.

name

..

" makes a sound."

)

end

-- Define the Dog class, inheriting from Animal

Dog

=

Animal

:

new

(

)

 

-- Dog inherits from the Animal class

-- Override the Dog class constructor

function

Dog

:

new

(

o

,

name

,

breed

)

  o

=

o

or

{

}

 

-- If no object is passed in, create a new empty table

 

setmetatable

(

o

,

self

)

 

-- Set the metatable so that it inherits Dog's and Animal's methods

  self

.

__index

=

self  

-- Allow the object to access Dog's methods

  o

.

name

=

name

or

"Unknown"

  o

.

breed

=

breed

or

"Unknown"

 

return

o

end

-- Override the Dog's sound method (override Animal's speak method)

function

Dog

:

speak

(

)

 

print

(

self

.

name

..

" barks."

)

end

-- Create an Animal object

local

animal

=

Animal

:

new

(

nil

,

"Generic Animal"

)

animal

:

speak

(

)

 

-- Output "Generic Animal makes a sound."

-- Create a Dog object

local

dog

=

Dog

:

new

(

nil

,

"Buddy"

,

"Golden Retriever"

)

dog

:

speak

(

)

 

-- Output "Buddy barks."

Running result:


Generic Animal makes a sound.
Buddy barks.

Polymorphism

Lua's polymorphism is implemented through metatables and method overriding. When objects of different types call the same method, Lua executes different methods according to the object's actual type.

Example

-- Define a "class" (actually a table)

Person

=

{

}

-- Add a constructor to the "class"

function

Person

:

new

(

name

,

age

)

   

local

obj

=

{

}

 

-- create a new table as the object

   

setmetatable

(

obj

,

self

)

 

-- Set the metatable to indicate that it is an instance of the Person class

    self

.

__index

=

self  

-- Set the __index metamethod pointing to Person

    obj

.

name

=

name

    obj

.

age

=

age

   

return

obj

end

-- Add a method

function

Person

:

greet

(

)

   

print

(

"Hello, my name is "

..

self

.

name

)

end

-- Define a subclass Student that inherits from Person

Student

=

Person

:

new

(

)

-- The subclass overrides the parent class's method

function

Student

:

greet

(

)

   

print

(

"Hi, I'm a student and my name is "

..

self

.

name

)

end

local

person2

=

Person

:

new

(

"Charlie"

,

25

)

local

student2

=

Student

:

new

(

"David"

,

18

)

-- Polymorphism: objects of different types call the same method

person2

:

greet

(

)

 

-- Output "Hello, my name is Charlie"

student2

:

greet

(

)

 

-- Output "Hi, I'm a student and my name is David"

Although person2 and student2 call the same greet method, because their types are different, Lua calls the version appropriate to each.

Running result:

Hello, my name is Charlie
Hi, I'm a student and my name is David

Other object-oriented concepts

Encapsulation

Encapsulation is usually implemented by wrapping data and methods in a table. We can simulate encapsulation by controlling access to the table, for example using metamethods to restrict external access.

Example

-- Define a "class" (actually a table)

Person

=

{

}

-- Add encapsulation: hide properties

function

Person

:

new

(

name

,

age

)

   

local

obj

=

{

}

   

setmetatable

(

obj

,

self

)

    self

.

__index

=

self

    obj

.

name

=

name

    obj

.

age

=

age

   

return

obj

end

function

Person

:

setName

(

name

)

    self

.

name

=

name  

-- Provide a method to modify name

end

function

Person

:

getName

(

)

   

return

self

.

name  

-- Provide a method to get name

end

In this way, we can control access to properties and simulate encapsulation.

Abstraction

Abstraction refers to simplifying complex things and hiding unnecessary details. Although Lua itself has no concept of classes, we can achieve abstraction through encapsulation.

Example

-- Only expose the interface, not the implementation details

function

Person

:

showInfo

(

)

   

print

(

"Name: "

..

self

.

name

)

   

print

(

"Age: "

..

self

.

age

)

end