Lua 程式設計中的命名引數


我們知道,當我們在任何程式語言中將引數傳遞給函式時,它們會與引數匹配。第一個引數的值將儲存在第一個引數中,第二個引數的值將儲存在第二個引數中,以此類推。

示例

考慮下面顯示的示例 -

local function A(name, age, hobby)
   print(name .. " is " .. age .. " years old and likes " .. hobby)
end

A("Mukul", 24, "eating")

輸出

Mukul is 24 years old and likes eating

如果我們仔細地將引數傳遞給它所屬的引數,上面的示例可以正常工作,但想象一下我們搞混了的情況。

示例

考慮下面顯示的示例 -

local function A(name, age, hobby)
   print(name .. " is " .. age .. " years old and likes " .. hobby)
end

A("Mukul", "eating", 24)

輸出

Mukul is eating years old and likes 24

現在一切都混亂了!

現在,如果我們可以給我們的引數命名以避免這種混亂,那會怎樣呢?給我們的引數命名的語法略有不同。

示例

考慮下面顯示的示例 -

local function B(tab)
   print(tab.name .. " is " .. tab.age .. " years old and likes " .. tab.hobby)
end

local mukul = {name="Mukul", hobby="football", age="over 9000", comment="plays too much football"}

B(mukul)

輸出

Mukul is over 9000 years old and likes football

更新於: 2021-12-01

1 千次瀏覽

開啟你的 職業生涯

透過完成課程獲得認證

開始
廣告
© . All rights reserved.