具名实参:指具有名称的实参。
将所有实参组织到一个table中,并将这个table作为唯一的实参传给函数。
对于参数很多的函数,有时很难记住参数的名字和参数的顺序以及哪些参数是可选的。通过table可以在调用这类函数时可以随意指定参数的顺序,并且可以只传递需要设定的参数。这就是具名实参的好处。
函数的参数机制中,最基础的方式是在调用一个函数时,实参通过它在参数中的位置与形参匹配起来。
function createPanel(x, y, width, height, background ,border) print(x) print(y) print(width) print(height) print(background) print(border) end createPanel(1,2,200,160,"white",1) --参数列表很长的时候,我们很难记起每个参数的具体含义 -- result: -->1 -->2 -->200 -->160 -->white -->1以这种方式调用函数,在函数参数列表较长的时候,很难记清各个参数代表什么意思,如果我们给实参指定具体的名字,就可以通过名称来轻松匹配形参。我们将所有实参组织到一个table中作为函数唯一的参数,来实现具名实参。
function createPanel( opt ) print(opt.x) print(opt.y) print(opt.width) print(opt.height) print(opt.background) print(opt.border) end createPanel({x=1,y=2,width=200,height=160,background="white",border=1}) -- 参数是匿名table -- result: -->1 -->2 -->200 -->160 -->white -->1 dataTable = {x=1,y=2,width=200,height=160,background="white",border=1} createPanel(dataTable) --另一种写法 -- result: -->1 -->2 -->200 -->160 -->white -->1有的时候,我们为一些参数设置了默认值,只想为某些参数赋值,其他参数使用默认值。这种情况下我们借助具名实参和另外一个函数来实现可选参数函数。
--[[createPanel函数可以根据要求检查一些必填的函数,或者为某些值添加默认值。"_createPanel"才是真正用于创建窗口的函数]] -- 用于检查参数和设置默认参数值的函数 function createPanel( opt ) -- 检查参数类型 if type(opt.height) ~= "number" then error("no height") end if type(opt.width) ~= "number" then error("no width") end -- width和height为必填的具名参数,其他参数可选 _createPanel(opt.x or 0, --默认值为0 opt.y or 0, --默认值为0 opt.width , --无默认值 opt.height, --无默认值 opt.background or "white", --默认值为“white” opt.border or 1) --默认值为1 end -- 真正实现功能的函数 function _createPanel( x, y , width , height, background, border) print(x) print(y) print(width) print(height) print(background) print(border) end使用可选参数函数
createPanel({x=1,y=2,width=200,height=160,background="white",border=1}) -- result: 为每个参数赋值 -->1 -->2 -->200 -->160 -->white -->1 createPanel({width = 200,height = 100}) -- result: 只为width、height赋值 -->0 -->0 -->200 -->100 -->white -->1 createPanel({x=1,y=2}) -- result: 出错 函数参数width和height没有默认值必须为其赋值,否则会出错参考: https://my.oschina.net/u/223340/blog/292163?p={{totalPage}} http://blog.csdn.net/fuyuehua22/article/details/38687061 http://blog.csdn.net/vermilliontear/article/details/50518679
