A brief example of lua’s object-oriented programming infrastructure table

Time:2021-10-10

object-oriented programming

Object oriented programming (OOP) is a very popular computer programming architecture.

LuaThe most basic structure istableTherefore, you need to use table to describe the properties of the object.

Function in Lua can be used to represent methods. Then the classes in Lua can be simulated through Table + function.

Brief example:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
--Czhenya Lua object oriented
--For an object, the property method
--[[two ways to define functions
person.eat = function()
  Print (person. Name.. "writing Lua")
end
function person.eat()
  Print (person. Name.. "writing Lua")
end
--]]
--As a prototype
Person = {name = 'Czhena',age = 22}
function Person:eat()
  Print (the age of self. Name.. "is".. self. Age)
end
function Person:new(o)   -- If O is empty, false is returned
  local t = o or {}
  --[[the result is the same as the following settings, but in two different ways
  setmetatable{t,self}
  self.__index=self
  --]]
  setmetatable(t,{__index = self})   -- Set meta table
  --When a property is called, if it does not exist in T, it will be__ Search in the table referred to by index
  return t
end
--It is similar to creating objects through constructors
person1 = Person:new({weight = 100})
person2 = Person:new()
print(person1.name)
print(person1.weight)
print(person2.name)
person1.name = "CZY"   -- The meta table will not be changed and added to person.name
person1:eat()
person2:eat()
--Inherit
Student = Person:new()
Student.grade = 1
stu1 = Student:new()
stu1:eat()
print(stu1.grade)

Difference between colon and point definition function:

?
1
2
3
4
5
6
7
8
9
10
11
--Use colons and points to define functions. It is recommended to define functions and call them
person = {name="Czhenya",age=22}
function person:eat()
  Print (the age of self. Name.. "is".. self. Age)
end
person.eat(person)
a = person
--Colon calls self auto assignment
a:eat()
--When calling through points, self will not be assigned automatically, but must be passed through parameters
a.eat(a)

summary

The above is the whole content of this article. I hope the content of this article has a certain reference value for your study or work. Thank you for your support for developepper. If you want to know more about it, please check the relevant links below

Recommended Today

SQL exercise 20 – Modeling & Reporting

This blog is used to review and sort out the common topic modeling architecture, analysis oriented architecture and integration topic reports in data warehouse. I have uploaded these reports to GitHub. If you are interested, you can have a lookAddress:https://github.com/nino-laiqiu/TiTanI recorded a relatively complete development process in my hexo blog deployed on GitHub. You can […]