Lua默认没有面向对象的概念,需要自己实现
(一)声明类,调用类里的成员变量和方法
--类和结构体
--c#中类有成员变量和成员函数,lua没有面向对象的概念要自己实现
--定义类
student={
--name
name="root",
--age
age=13,
--upper function
upper=function()
print("I level up")
end,
--study function
study=function()
print("I am studying")
end
}
--使用类
print(student.age)--13
student.upper()--I level up
--在表外声明,成员变量和成员函数
student.sex="false"
student.speak=function()
print("speak quickly")
end
print(student.sex)--false
student.speak()--speak quickly
function student.eat()
print("eating")
end
student.eat()--eating
--如果要在表内部使用成员
--第一种方法
student.eat=function ()
print(age)--age并不是13,而是nil,这个age是个全局变量
print(student.age)--这个才代表是表内的成员变量age,打印13
print("eating")
end
student.eat()--age并不是13,而是nil
--第二种方法,传参数
student.eat=function (t)
print(t.age)
end
student.eat(student)--13
--第三种方法,用冒号
--冒号调用方法,会默认把调用者作为第一个参数传入方法中,且冒号不能在表内使用,只有在表外声明
--点号如果有参数,必须传入参数
student:eat()--13
function student:eat()--这里是默认传了student作为参数的
print(student.age)
print(self.name)--self表示默认函数传入的第一个参数,不是this的意思
end
student:eat()--13
--[[student:eat()=function()--这种写法就报错了
print(student.age)
end]]
(二)在表外声明,成员变量和成员函数
--在表外声明,成员变量和成员函数
student.sex="false"
student.speak=function()
print("speak quickly")
end
print(student.sex)--false
student.speak()--speak quickly
function student.eat()
print("eating")
end
student.eat()--eating
(三)如果要在表内部使用成员
--如果要在表内部使用成员
--第一种方法
student.eat=function ()
print(age)--age并不是13,而是nil,这个age是个全局变量
print(student.age)--这个才代表是表内的成员变量age,打印13
print("eating")
end
student.eat()--age并不是13,而是nil
--第二种方法,传参数
student.eat=function (t)
print(t.age)
end
student.eat(student)--13
--第三种方法,用冒号
--冒号调用方法,会默认把调用者作为第一个参数传入方法中,且冒号不能在表内使用,只有在表外声明
--点号如果有参数,必须传入参数
student:eat()--13
function student:eat()--这里是默认传了student作为参数的
print(student.age)
print(self.name)--self表示默认函数传入的第一个参数,不是this的意思
end
student:eat()--13
student.eat(student)--13 root,这样写也不会报错
--[[student:eat()=function()--这种写法就报错了
print(student.age)
end]]
(四)点号、冒号,self
1.冒号调用方法,会默认把调用者作为第一个参数传入方法中,且冒号不能在表内使用,只有在表外声明
2.点号如果有参数,必须传入参数
3.self表示默认函数传入的第一个参数,不是this的意思