什么是具名实参
顾名思义 具有名字的实参
具名实参的存在意义
当一个函数有很多参数的时候,有时很难记住参数的名字和顺序以及哪些参数是可赋值的。这里就可以通过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})
输出
1
2
200
160
white
1
还有一个功能类似于属性,可以对字段进行封装
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({width=200,height=160,background="white",border=1})
输出
0
0
200
160
white
1
因为这里的x和y默认值为0,不传参时使用默认值。