lua中的table就是一种对象,例如
- Test1 = {
- x = nil,y = nil,}
- --创建一个新表
- function Test1:new()
- --如果参数中没有提供table,则创建一个空的。
- local o = o or {}
- --将新对象实例的Metatable指向Test1表(类),这样就可以将其视为模板了。
- setMetatable(o,self);
- --在将Test1的__index字段指向自己,以便新对象在访问Test1的函数和字段时,可被直接重定向。
- self.__index = self;
- return o;
- end
- function Test1:setXY(x,y)
- self.x = x;
- self.y = y;
- end
- function Test1:getXY()
- print("x="..self.x.." y="..self.y)
- return self.x,self.y
- end
- function Test1:setX(x)
- self.x=x
- end
- function Test1:getX()
- return self.x
- end
- function Test1:setY(y)
- self.y=y
- end
- function Test1:getY()
- return self.y
- end
在main.lua中使用
- require("src/Test1")
- local t1 = Test1:new();
- local t2 = Test1:new();
- t1:setXY(2,5)
- t2:setXY(8,2)
- -- t1:getXY()
- -- t2:getXY()
- print(t1:getXY())
看看输出
- cocos2d: [LUA-print] x=2 y=5
- cocos2d: [LUA-print] 2 5