English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Lua 面向对象

Object-Oriented Programming (OOP) is a very popular computer programming architecture.

The following programming languages all support object-oriented programming:

  • C++

  • Java

  • Objective-C

  • Smalltalk

  • C#

  • Ruby

Object-Oriented Features

  • 1) Encapsulation: It refers to the characteristic of being able to put the information, function, and response of an entity into a single object.

  • 2) Inheritance: The inheritance method allows the expansion of the program without changing the original program, so that the original function can be preserved, and the new function can also be expanded. This is conducive to reducing repeated coding and improving the development efficiency of software.

  • 3) Polymorphism: The same operation can have different interpretations on different objects, resulting in different execution results. At runtime, methods in derived classes can be called through pointers pointing to the base class.

  • 4) Abstraction: Abstraction is a way to simplify complex real-world problems, it can find the most appropriate class definition for specific problems, and can explain problems at the most appropriate level of inheritance.

Object-Oriented in Lua

We know that objects are composed of properties and methods. The most basic structure in LUA is table, so it is necessary to use table to describe the properties of objects.

Functions in Lua can be used to represent methods. Therefore, classes in LUA can be simulated through table + function.

As for inheritance, it can be simulated through metatable (not recommended to use, it is enough to simulate the basic object most of the time).

In Lua, tables are not only objects in a certain sense. Like objects, tables also have state (member variables); they also have an independent nature that is independent of the value of the object (table), especially when two different value objects (table) represent two different objects; an object can also have different values at different times, but it is always an object; like objects, the lifecycle of tables is not related to what created them or where they were created. Objects have their member functions, and tables also have them:

Account = {balance = 0}
function Account:withdraw(v)
    Account.balance = Account.balance - v
end

Questa definizione crea una nuova funzione e la salva nel dominio del metodo dell'oggetto Account, quindi possiamo chiamarla in questo modo:

Account:withdraw(100.00)

Esempio semplice

Di seguito, una classe semplice contiene tre proprietà: area, length e breadth, il metodo printArea viene utilizzato per stampare i risultati del calcolo:

-- Metaclasse
Rectangle = {area = 0, length = 0, breadth = 0}
-- Metodi della classe derivata new
function Rectangle:new (o,length,breadth)
  o = o or {}
  setmetatable(o, self)
  self.__index = self
  self.length = length or 0
  self.breadth = breadth or 0
  self.area = length * breadth;
  return o
end
-- Metodi della classe derivata printArea
function Rectangle:printArea ()
  print("矩形面积为 ",self.area)
end

Creazione dell'oggetto

Creare un oggetto è il processo di allocazione della memoria per l'esempio della classe. Ogni classe ha la propria memoria e condivide i dati pubblici.

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

Accesso alle proprietà

Possiamo utilizzare il punto . per accedere alle proprietà della classe:

print(r.length)

Accesso ai metodi membri

Possiamo utilizzare il due punti : per accedere ai metodi membri della classe:

r:printArea()

La memoria viene allocata all'inizializzazione dell'oggetto.

Esempio completo

Di seguito, mostriamo un esempio completo di programmazione orientata agli oggetti in Lua:

-- Metaclasse
Shape = {area = 0}
-- 方法 new di base
function Shape:new(o, side)
  o = o or {}
  setmetatable(o, self)
  self.__index = self
  side = side or 0
  self.area = side * side;
  return o
end
-- 方法 printArea di base
function Shape:printArea()
  print("Area: ", self.area)
end
-- 创建对象
myshape = Shape:new (nil,10)
myshape:printArea ()

Eseguendo il programma sopra, il risultato di output sarà:

面积为 100

Ereditarietà Lua

L'ereditarietà si riferisce a un oggetto che utilizza direttamente le proprietà e i metodi di un altro oggetto. Può essere utilizzata per estendere le proprietà e i metodi della classe di base.

Ecco un esempio semplice di ereditarietà:

-- Meta classe
Shape = {area = 0}
-- 方法 new di base
function Shape:new(o, side)
  o = o or {}
  setmetatable(o, self)
  self.__index = self
  side = side or 0
  self.area = side * side;
  return o
end
-- 方法 printArea di base
function Shape:printArea()
  print("Area: ", self.area)
end

Nell'esempio seguente, l'oggetto Square eredita la classe Shape:

Square = Shape:new ()
-- Metodi della classe derivata new
function Square:new (o,side)
  o = o or Shape:new(o,side)
  setmetatable(o, self)
  self.__index = self
  return o
end

Esempio completo

Nell'esempio seguente, abbiamo ereditato una classe semplice per estendere i metodi della classe derivata, la classe derivata mantiene i membri variabili e i metodi della classe ereditata:

-- Meta classe
Shape = {area = 0}
-- 方法 new di base
function Shape:new(o, side)
  o = o or {}
  setmetatable(o, self)
  self.__index = self
  side = side or 0
  self.area = side * side;
  return o
end
-- 方法 printArea di base
function Shape:printArea()
  print("Area: ", self.area)
end
-- 创建对象
myshape = Shape:new (nil,10)
myshape:printArea ()
Square = Shape:new ()
-- 派生类方法 new
function Square:new (o,side)
  o = o or Shape:new(o,side)
  setmetatable(o, self)
  self.__index = self
  return o
end
-- 派生类方法 printArea
function Square:printArea ()
  print("正方形面积为 ",self.area)
end
-- 创建对象
mysquare = Square:new (nil,10)
mysquare:printArea ()
Rectangle = Shape:new ()
-- 派生类方法 new
function Rectangle:new (o,length,breadth)
  o = o or Shape:new(o)
  setmetatable(o, self)
  self.__index = self
  self.area = length * breadth
  return o
end
-- 派生类方法 printArea
function Rectangle:printArea ()
  print("矩形面积为 ",self.area)
end
-- 创建对象
myrectangle = Rectangle:new (nil,10,20)
myrectangle:printArea ()

执行以上代码,输出结果为:

面积为 100
正方形面积为 100
矩形面积为 200

函数重写

在 Lua 中我们可以重写基础类的函数,在派生类中定义自己的实现方式:

-- 派生类方法 printArea
function Square:printArea ()
  print("正方形面積 ",self.area)
end