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,不傳參時使用默認值。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章