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

对于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函数

相关文章

    本文实践自 RayWenderlich、Ali Hafizji 的文章《...
Cocos-code-ide使用入门学习地点:杭州滨江邮箱:appdevzw@1...
第一次開始用手游引擎挺激动!!!进入正题。下载资源1:从C...
    Cocos2d-x是一款强大的基于OpenGLES的跨平台游戏开发...
1.  来源 QuickV3sample项目中的2048样例游戏,以及最近《...
   Cocos2d-x3.x已经支持使用CMake来进行构建了,这里尝试...