面向对象定义方法

面向对象
对象:属性、方法。
table,function。

student = {name = "张三",age = 18,
gotoSchool = function(name)
 print(name.."上学")
end}
--[[
student.gotoSchool = function(name)
 print(name.."上学")
end
function student.gotoSchool(name)
 print(name.."上学")
end
]]--
print("学生姓名:"..student.name..",年龄是:"..student.age)
student.gotoSchool(student.name)

技巧冒号
1。类比:一个类,实例化多个对象。

Student = {name = "默认名称"}
function Student:new()
	-- 我们要返回的对象
	s = {}
	setmetatable(s,{__index=self})
	return s

end
s1 = Student:new()
s2 = Student:new()
print("s1..",s1.name)
print("s2..",s2.name)

s1.name = "李四"
s2.name = "王五"
print("s1..",s1.name)
print("s2..",s2.name)
posted @ 2022-07-26 20:39  再努力一些  阅读(27)  评论(0)    收藏  举报