Slog55_lua面向对象之lua类
-
ArthurSlog
-
SLog-55
-
Year·1
-
Guangzhou·China
-
Aug 30th 2018
-
GitHub
-
掘金主页
-
简书主页
-
segmentfault
现实中的事情不是根据人的喜好而定的 比如长在你嘴里的智齿 大部分情况下 你会因为自己(的牙)而痛苦 直到忍痛拔掉 鲜血淋漓 也许痛过之后 才能回归正途
开发环境MacOS(High Sierra 10.13.5)
需要的信息和信息源:
-
github 完整代码
-
Object-Oriented Programming
-
Classes
-
Classes Inheritance
-
Classes Multiple Inheritance
-
Classes Privacy
-
Classes The Single-Method Approach
-
require
-
package
-
package Basic Approach
-
package Privacy
-
Packages and Files
-
Using the Global Table
-
Other Facilities
-
Programming in Lua
开始编码
- 完整代码:
~/Desktop/lua_learningload/lua_class/Employee.lua
-- 文件名为 EmployeePackage.lua
-- 定义一个名为 EmployeePackage 的模块
-- Meta class
EmployeePackage = {empCount = 0, name = '0', salary = 0}-- 派生类的方法 new
function EmployeePackage:new (o,name,salary)e = e or {}setmetatable(e, self)self.__index = selfself.empCount = self.empCount + 1self.name = nameself.salary = salaryreturn e
end-- 派生类的方法 printArea
function EmployeePackage:info ()print("Total Employee ", self.empCount)print("Name : " , self.name) print("Salary: " , self.salary)
endemp = Employee:new(nil,'xiaoming',1024)emp:info()
复制代码
- 其中,Employee类如下:
~/Desktop/lua_learningload/lua_class/Employee/lua
-- 文件名为 EmployeePackage.lua
-- 定义一个名为 EmployeePackage 的模块
-- Meta class
EmployeePackage = {empCount = 0, name = '0', salary = 0}-- 派生类的方法 new
function EmployeePackage:new (o,name,salary)e = e or {}setmetatable(e, self)self.__index = selfself.empCount = self.empCount + 1self.name = nameself.salary = salaryreturn e
end-- 派生类的方法 printArea
function EmployeePackage:info ()print("Total Employee ", self.empCount)print("Name : " , self.name) print("Salary: " , self.salary)
end
复制代码
- 现在,切换至文件路径下
cd ~/Desktop/lua_learningload/lua_class/Employee.lua
- 执行lua文件
lua ./Employee.lua
- 执行结果:
Total Employee 1
Name : xiaoming
Salary: 1024
复制代码
- 另一方面,根据上一篇文章所讲,上面的这个lua类也可以作为一个lua包,在新的程序里导入
~/Desktop/lua_learningload/lua_class/
-- Meta class
EmployeePackage = {empCount = 0, name = '0', salary = 0}-- 派生类的方法 new
function EmployeePackage:new (o,name,salary)e = e or {}setmetatable(e, self)self.__index = selfself.empCount = self.empCount + 1self.name = nameself.salary = salaryreturn e
end-- 派生类的方法 printArea
function EmployeePackage:info ()print("Total Employee ", self.empCount)print("Name : " , self.name) print("Salary: " , self.salary)
endreturn EmployeePackage
复制代码
~/Desktop/lua_learningload/lua_class/EmployeePackage.lua
-- run.lua 文件
-- EmployeePackage 模块为上文提到到 EmployeePackage.lua
-- 别名变量 p
local p = require("EmployeePackage")emp = p:new(nil,'xiaoming',1024)emp:info()
复制代码
- 现在,切换至文件路径下
cd ~/Desktop/lua_learningload/lua_class/
- 执行lua文件
lua ./run.lua
- 执行结果:
Total Employee 1
Name : xiaoming
Salary: 1024
复制代码
- 至此,我们实现了一个lua类,并把这个lua类打包供其他lua程序使用。