您的位置:首页 > 移动开发 > Cocos引擎

如何给quick-cocos2d-x的model类自动添加get和set函数

2015-03-31 14:31 183 查看
对于model类,如果比较正式的话,访问属性应当采用get和set的方式,当该类属性比较多,而且大量都是直接读取时,增加一个自动生成get和set函数的操作

就会比较方便,这样只需要针对特殊的属性单独写get和set即可

1.首先先简单说明一下如何给类动态定义成员函数名

lua的函数名是可以动态配置的

方法是

类名[函数名] = function定义

例如:

1)

--创建一个对象

local myClass = class("myClass").new()

--动态给一个函数名

local functionName = "myFunctionName"

--用对象["函数名"] = function定义的方式关联

myClass[functionName] = function(target, value)

print("in function ".."myFunctionName")

print(target)

print(value)

end

--用正常方式调用

myClass:myFunctionName("value1")

输出结果为

[LUA-print] in function myFunctionName

[LUA-print] table

[LUA-print] value1

2)

myClass.f2 = myClass[functionName]

myClass:f2("ddd")

输出结果为

[LUA-print] in function myFunctionName

[LUA-print] table

[LUA-print] ddd

2.下面说一下如何生成set和get函数

注意该函数只适用于从quick cocos2dx中mvc框架的cc.mvc.ModelBase类派生,而且采用schema定义属性的情况

--自动添加get和set函数

local function initGetterAndSetter(target)

if target.schema and type(target.schema)=="table" and #target.schema then

for field,typ in pairs(target.schema) do

--首字母变大写

local uname = string.ucfirst(field)

local gfname = "get"..uname)

--如果代码没有特殊写该属性的get函数,则自动生成

if (not target[gfname]) then

target[gfname] = function(target)

return target[field.."_"]

end

end

local sfname = "set"..uname

local vtype = typ

if type(typ) == "table" then

vtype = typ[1]

end

--如果代码没有特殊写该属性的set函数,则自动生成

if (not target[sfname]) then

target[sfname] = function(target,value)

if value == nil then return end

if vtype == "string" then

value = tostring(value)

elseif vtype == "number" then

value = checknumber(value)

end

if type(value) == vtype then target[field.."_"] = value end

end

end

end

end

end

在该类的构造函数中调用,例如

function TestModel:ctor(properties)

TestModel.super.ctor(self,properties)

initGetterAndSetter(self)

end

假设属性为

TestModel2.schema["sizex"] = {"number", 0}

就会自动生成

getSizex函数和setSizex函数
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  cocos2d-x lua mvc