Lua 语言本身是非常简单的(相对于 C#,C++,Java …),由于 Lua 语言的创始人的初衷,就是设计一款简单而又小巧的语言,所以说 Lua语言本身是没有“类和对象”的概念的。
类定义模拟
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
| Person = {name, age, gender}
<! Person.Id = 1
function () 4local object = {} 4setmetatable(object, Person) 4self.__index = Person 4return object end
function Person.Print() 4print("Print something") end
function Person:Show() 4print(self.name, self.age, self.gender) end
|
类调用模拟
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
| zak = Person:New() zak.name = "zak" zak.age = 18 zak.gender = "男" kyle = Person:New() kyle.name = "kyle" kyle.age = 16 kyle.gender = "男"
print(Person.Id) print(zak.Id) print(kyle.Id)
Person.Print()
zak:Show() kyle:Show()
|
继承模拟
1 2 3 4 5 6 7 8 9 10 11 12
| Programer = Person:New()
function Programer:New() 4local object = Person:New() 4setmetatable(object, Programer) 4self.__index = Programer 4return object end
function Programer:Code() 4print(self.name.." is coding") end
|
调用
1 2 3 4 5 6
| zac = Programer:New() zac.name = "zac" zac.age = 20 zac.gender = "男" zac:Show() zac:Code()
|
代码分离
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39
| Hero = {name}
function Hero:New() 4local object = {} 4setmetatable(object, self) 4self.__index = self 4return object end
function Hero:Info() 4print("Hero's name : " .. self.name) end
Enemy = {name}
function Enemy:New() 4local object = {} 4setmetatable(object, self) 4self.__index = self 4return object end
function Enemy:Info() 4print("Enemy's name : " .. self.name) end
dofile("Hero.lua") dofile(".\Enemy.lua")
hero = Hero:New() hero.name = "a" hero:Info()
enemy = Enemy:New() enemy.name = "b" enemy:Info()
|