根据上一节知识所述Lua中没有像C、C++、JAVA中的类概念,面向对象等 ,但我们可以模拟出来
如下
代码如下:
--创建类的表
local Person = {}
function Person:setName()
print("Person:setName()")
end
--.....
--new实例函数
function Person:new(instance)
if not instance then
instance = {}
end
local meta_Person = {
__index = self,
}
setmetatable(instance,meta_Person)
return instance
end
--实例化
local man = Person:new()
man.setName() --Person:setName()
--实例化二
local woman = Person:new({
name = "xiaohong",
age = 24,
sex = 1,
})
print(woman.name)
print(woman.setName)
面向对象的基本步骤:
--(1)定义一个类的表;
--(2)定义一个实例的表;
--(3)为这个实例的表加一个元素,并且元表__index指向了这个类的表;
--(4)利用self机制,表的实例:表的函数的时候,隐式的帮我们传递了这个实例的表为self到函数里面;
|
请发表评论