微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

如何给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函数

原文地址:https://www.jb51.cc/cocos2dx/343683.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐