Lua 中没有类的概念,但通过 table、function 与元表可以模拟和构造出具有类这样功能
的结构。
1.简单对象的创建
Lua 中通过 table 与 fcuntion 可以创建出一个简单的 Lua 对象:table 为 Lua 对象赋予属
性,通过 function 为 Lua 对象赋予行为,即方法。
现有如下两个对象
--创建一个animal对象
animal = {att = "动物", name = "无名", age = 1, des = "描述", bark = "汪汪"}
animal.setAtt = function(str)
animal.att = str
end
animal.setName = function(str)
animal.name = str
end
animal.setAge = function(age)
animal.age = age
end
animal.setDes = function(des)
animal.des = des
end
animal.setBark = function(strBark)
animal.bark = strBark
end
animal.tostring = function()
if (animal == nil) then
print("animal为空了")
return
end
str = animal.att.." "..animal.name.." "..animal.age.." "..animal.des.." "..animal.bark
print(str)
end
animal.tostring()
animal.setName("二哈")
animal.tostring()
anima2 = animal --相当于c++中的浅复制
当 animal = nil 置空后,anima2会出现无法继续访问animal对象中的方法。
如下:
animal = nil --执行这串代码后anima2相当于c中的野指针了(也不完全是,只是无法正确调用函数,其余值还是可以的)
anima2.tostring()
//输出结果:
动物 无名 1 描述 汪汪
动物 二哈 1 描述 汪汪
animal为空了
解决办法:用另外一种方式实现tostring(),如下:
function animal:tostring()
if (self == nil) then
print("self为空了")
return
end
str = self.att.." "..self.name.." "..self.age.." "..self.des.." "..self.bark
print(str)
end
--注意:此时访问也用 : 号 如:
anima2:tostring()
//输出结果如下:
动物 无名 1 描述 汪汪
动物 二哈 1 描述 汪汪
动物 二哈 1 描述 汪汪
标签:function,end,str,..,面向对象,self,16,lua,animal
From: https://www.cnblogs.com/gom-linwei/p/18133548