Lua中的具名实参(named arguments)

什么是具名实参

顾名思义 具有名字的实参

具名实参的存在意义

当一个函数有很多参数的时候,有时很难记住参数的名字和顺序以及哪些参数是可赋值的。这里就可以通过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,不传参时使用默认值。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值