lua学习笔记之一(C/C++程序员的Lua快速入门[初阶话题])(二)

2014-11-24 01:02:39 · 作者: · 浏览: 6
...) ... end 等价于obj.method = function (self, a1, a2, ...) ... end
成员方法的调用
obj:method(a1, a2, ...) 等价于obj.method(obj, a1, a2, ...)
5.简单继承*
5.1 实现代码
[plain]
local function CreateRobot(name,id)
local obj = {name = name,id = id}
function obj:SetName(name)
self.name = name
end
function obj:GetName()
return self.name
end
function obj:SetId(id)
self.id = id
end
function obj:GetId()
return self.id
end
return obj
end
local function createFootballRobot(name ,id ,position)
local obj = CreateRobot(name ,id)
obj.position = "right back"
function obj:SetPosition(p)
self.position = p
end
function obj:GetPosition()
return self.position
end
return obj
end
local mycreateFootballRobot = createFootballRobot("Tom",1000,"广州")
print("mycreateFootballRobot's name:",mycreateFootballRobot:GetName(),"myCreate's id:",mycreateFootballRobot:GetId(),mycreateFootballRobot:GetPosition())
mycreateFootballRobot:SetName("麦迪")
mycreateFootballRobot:SetId(2000)
mycreateFootballRobot:SetPosition("北京")
print("mycreateFootballRobot's name:",mycreateFootballRobot:GetName(),"myCreate's id:",mycreateFootballRobot:GetId(),mycreateFootballRobot:GetPosition())
输出结果:
mycreateFootballRobot's name:TommyCreate's id:1000right back
mycreateFootballRobot's name:麦迪myCreate's id:2000北京