Let’s take a look at a program:
Copy the codeThe code is as follows:
function create(name, id)
local obj = { name = name, id = id }
function obj:SetName(name)
= name
end
function obj:GetName()
return
end
function obj:SetId(id)
= id
end
function obj:GetId()
return
end
return obj
end
o1 = create("Sam", 001)
print("o1's name:", o1:GetName(), "o1's id:", o1:GetId())
o1:SetId(100)
o1:SetName("Lucy")
print("o1's name:", o1:GetName(), "o1's id:", o1:GetId())
Output result:
Copy the codeThe code is as follows:
o1's name: Sam o1's id: 1
o1's name: Lucy o1's id: 100
Object factory pattern:
The create function like the previous code
Use table to represent objects:
Put the object's data and methods into a table. Although there are no private members hidden, it is completely acceptable for simple scripts.
Definition of member methods:
Copy the codeThe code is as follows:
function obj:method(a1,a2,…)…end --equivalent to
function (self,a1,a2,…)…end --equivalent to
=function(self,a1,a2,...)...end
Calling member methods:
Copy the codeThe code is as follows:
obj:method(a1,a2,...) --equivalent to
(obj,a1,a2,...)