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