-- 作用: 错误处理 localfunction() returnerror("Invalid argument types to overload function.") end
--作用:(相同函数名+入参不同)的调用触发在funcList中依据入参列表的类型查找有无对应函数 functionmt:__call(...) local default=self.default local paramTypeList={} --用于存放入参类型的列表 for i,param inipairs({...}) do paramTypeList[i]=type(param) end paramTypeList=table.concat(paramTypeList,",") return (funcList[paramTypeList]or self.default)(...) end
-- 作用:多个入参重载时,由于前面的索引是通过检索操作触发的,会进入__index函数 functionmt:__index(key) local paramTypeList={} --用于存放入参类型的列表 -- 多参数配置时,最后一个参数的入口,因为最后一个索引操作相当于是在给该索引赋值一个函数 -- 该函数不能写在__index下面,因为__index里要注册该函数为最后一个入参的赋值函数 localfunction__newindex(self,key,value) print("nThe Last param is "..key..". No Same input-params-func in List,Add a new-Input-Param-Types-function.") paramTypeList[#paramTypeList+1]=key funcList[table.concat(paramTypeList, ",")]=value --将该入参列表设置为当前注册的函数 print("Overload a new function with input-params are:".."("..table.concat(paramTypeList, ",")..")") end
-- 多参数配置时,除最后一个参数外的入口,因为设置前面参数的操作本质上是索引self localfunction__index(self,key) print("nSearching "..tostring(self).." with next param type is "..key) -- 存储当前的入参,然后为其申请它的next-param查找列表,检索方式和现在相同,所以为其配置同样操作的元表 paramTypeList[#paramTypeList+1]=key local nextParamSearchTable={} print("and Next Search Table is "..tostring(nextParamSearchTable)) returnsetmetatable(nextParamSearchTable,{__index=__index,__newindex=__newindex}) end return__index(self,key) end -- 作用:单个入参重载时,直接设置key,value functionmt:__newindex(key,value) funcList[key]=value print("Overload a new function with input-params are:".."("..key..")") end
-- public
-- 作用:new函数返回一个可以进行重载功能的表 functionOverloadModule:new() returnsetmetatable({default=perror}, mt) end
functionnewItem.table(item) print("Creating by copy a item.") end
functionnewItem.string(name) print("Create a item by name.") end
functionnewItem.string.boolean.number.string(name,canSell,price,descrp) print("Create a item by name and its price(if can be sold) with description.") end
print("n") newItem("MagicBook",true,100,"This is a MagicBook.")
Output
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
Overload a new functionwithinput-paramsare:(table) Overload a new functionwithinput-paramsare:(string)
Searching table: 0x7faa7ec0b460 with next param type is string and Next Search Table is table: 0x7faa7ec03150
Searching table: 0x7faa7ec03150 with next param type is boolean and Next Search Table is table: 0x7faa7ec0b730
Searching table: 0x7faa7ec0b730 with next param type is number and Next Search Table is table: 0x7faa7ec0b950
The Last param is string. No Same input-params-func in List,Add a new-Input-Param-Types-function. Overloadanewfunctionwithinput-paramsare:(string,boolean,number,string)
Create a item by name and its price(if can be sold) with description. [Finished in0.0s]