天天看点

Cocos2d-x Lua游戏开发之Lua oo 的实现

一些面向对象的语言中提供了类的概念,作为创建对象的模版。在这些
语言里面。对象是类的实例,lua通过table也可以实现类的使用。

--建立父类Animal
Animal = {
	size,--动物大小       成员变量声明,不赋值为nil
	age,--动物年龄
	color = "yellow",--动物颜色
	sex,--动物性别,这个可以有??
	new = function ( self,object )
		object = object or {}--判断object是否为空,nil就会创建一个空的table
		setmetatable(object,self)--设置animal基类为元表,算是继承的方法
		self.__index = self --同上
		return object
	end,
	sleep = function ( self,pram )--lua支持:运算符,代替.运算符和显示self
		print(pram,"想要好好的睡觉")--人类尤其是,程序员,记住睡觉,no nuo no die
	end,
	run = function ( self,pram )
		print(pram,"想要好好的运动")--人类尤其是,程序员,记住运动,no nuo no die
	end,
	setAge = function ( self,age )--继承oc之set,get方法,看后面可否写成宏
		self.age = age--两个参数
		print("setAge=",self.age)
		return self.age
	end,
	getAge = function ( self )
		print("getAge=",self.age)
		return self.age
	end,
	getColor = function ( self )
		print("getColor=",self.color)
		return self.color
	end
}

Cat = Animal:new()--创建一个空对象
Cat:sleep("cat")
Cat.age = 22
Cat:setAge(0)
Cat:getAge()
Cat:getColor()

Snake = Animal:new{age = 33}
Snake:sleep("snake")
Snake:getAge()
function Snake:sleep( animal )--子类重写方法,即可实现子类自身
	print("snake 有了一个自己的小窝来睡觉")
end
Snake:sleep("snake")
           

csdn不支持lua,但是看着又不舒服,还是传张图片吧。使用的sublimetext

Cocos2d-x Lua游戏开发之Lua oo 的实现
Cocos2d-x Lua游戏开发之Lua oo 的实现